Home Backend Development PHP Tutorial How to write WeChat payment interface development program in PHP

How to write WeChat payment interface development program in PHP

Jun 01, 2018 pm 04:00 PM
php develop program

The WeChat payment interface is now slowly becoming like Alipay, which can use the API interface to implement third-party websites or applications for payment. The following is a php WeChat payment interface development program and has been tested. Interested friends can Please refer to

php WeChat payment interface development program explanation:

Required conditions:
appid //obtained from the official account backend developer center (Same as the one in the email)

mchid//Obtained in the email

key//Set up by the merchant backend

appsecret //Obtained in the official account developer center
Two certificate files, apiclient_cert.pem and apiclient_key.pem are obtained in the email
Notes:
Official account background WeChat payment - "Development configuration -" Add test directory and test personal WeChat account.
Developer Center-》Web page authorization to obtain basic user information-》Change to your test domain name. Otherwise, a redirect_uri parameter error will occur
——————————Follow-up to be improved——————-
The WeChat payment ready page has performed three operations on its own in the background:

1. Obtain openid

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

//使用jsapi接口

  

 代码如下复制代码

  $jsApi = new JsApi_pub();

  

  //=========步骤1:网页授权获取用户openid============

  //通过code获得openid

  if (!isset($_GET['code']))

  {

    //触发微信返回code码

    $url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL);

    //echo $url;

    Header("Location: $url");

  }else

  {

    //获取code码,以获取openid

    $code = $_GET['code'];

    $jsApi->setCode($code);

    $openid = $jsApi->getOpenid();

  }

Copy after login

When I first started, I also encountered problems in the first step, unable to obtain openid. Related to some servers, the demo uses the curl acquisition method.
It’s strange that my server curl has been unable to be obtained. Later, it was changed to file_get_contents and it can be obtained normally.
But this is not the solution. Because more curl operations will be needed later.
I saw a place in the development documentation where the certificate operation requires libcurl 7.20.1 or above. Then I have been working on the server to improve the php curl version of Linux. In the end, I just switched to another windows server.
Let’s do this for the time being, and debug it when we need to use it next time.

Second step: Get and pay order number id
The code is as follows

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

$unifiedOrder = new UnifiedOrder_pub();

    

  //var_dump($unifiedOrder);

  //设置统一支付接口参数

  //设置必填参数

  //appid已填,商户无需重复填写

  //mch_id已填,商户无需重复填写

  //noncestr已填,商户无需重复填写

  //spbill_create_ip已填,商户无需重复填写

  //sign已填,商户无需重复填写

  $unifiedOrder->setParameter("openid","$openid");//商品描述

  $unifiedOrder->setParameter("body","贡献一分钱");//商品描述

  //自定义订单号,此处仅作举例

  $timeStamp = time();

  $out_trade_no = WxPayConf_pub::APPID."$timeStamp";

  $unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号

  $unifiedOrder->setParameter("total_fee","1");//总金额

  $unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//通知地址

  $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型

  //非必填参数,商户可根据实际情况选填

  //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号

  //$unifiedOrder->setParameter("device_info","XXXX");//设备号

  //$unifiedOrder->setParameter("attach","XXXX");//附加数据

  //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间

  //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间

  //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记

  //$unifiedOrder->setParameter("openid","XXXX");//用户标识

  //$unifiedOrder->setParameter("product_id","XXXX");//商品ID

  

  

  $prepay_id = $unifiedOrder->getPrepayId();

    

  //echo 'prepay_id:';

  var_dump($prepay_id);

Copy after login

This step also encounters Got a lot of questions.
First of all, it is difficult to test WeChat payment, and it can only be tested within WeChat. I just use my phone to swipe around.
Secondly, it is not easy to use var_dump for debugging. Printing some files in xml format only displays the character length, not the content. So I wrote it in the form of log for debugging on the server. The log code:
The code is as follows

1

2

3

4

5

6

7

8

9

10

// 打印log

  function log_d($word)

  {

    $log_name="./logd.log";//log文件路径

    $fp = fopen($log_name,"a");

    flock($fp, LOCK_EX) ;

    fwrite($fp,"执行日期:".strftime("%Y-%m-%d-%H:%M:%S",time())."n".$word."nn");

    flock($fp, LOCK_UN);

    fclose($fp);

  }

Copy after login

Use $this- in WxPayPubHelper.php in the demo >log_d(xxx); called.
At the beginning, I kept getting errors because the mchid and appid given to me did not match. . They gave me the wrong account number. At the beginning, I didn’t know how to try randomly. For this step of debugging, you can see the error code using var_dump($this->result); in getPrepayId().

The third step: Generate the payment front-end js code and put it on the web page:
The code is as follows

1

2

3

$jsApi->setPrepayId($prepay_id);

  

$jsApiParameters = $jsApi->getParameters();

Copy after login

——————-Click to pay————————-

Another problem encountered in this part:
android returns "System: Access_denied", ios returns "access_control:not_allowed"
I searched a lot on Baidu. In fact, I have seen this thing for a long time and never noticed it!
The page that initiates the authorization request must be in the authorization directory and cannot exist in a subdirectory. Otherwise, an error will be returned
I placed the payment file in /domain name/pay/demo/
At the beginning, I always reached the end of /domain name/pay/ and thought that was enough. Support subdirectories, the result is not possible! .
————————Finally look at the picture below————

wxpay1
wxpay3
wxpay2

—— ————xmljs in the process——————–
Generation and payment order id to be submitted:
The code is as follows

1

2

3

4

5

6

7

8

9

10

11

12

13

<xml>

 <openid><![CDATA[ou9dHt0L8qFLI1foP-kj5x1mDWsM]]></openid>

 <body><![CDATA[贡献一下]]></body>

 <out_trade_no><![CDATA[wx88888888888888881414411779]]></out_trade_no>

 <total_fee>1</total_fee>

 <notify_url><![CDATA[http://shanmao.me/wxpay/notify_url.php]]></notify_url>

 <trade_type><![CDATA[JSAPI]]></trade_type>

 <appid><![CDATA[wx8888888888888888]]></appid>

 <mch_id>10012345</mch_id>

 <spbill_create_ip><![CDATA[61.50.221.43]]></spbill_create_ip>

 <nonce_str><![CDATA[60uf9sh6nmppr9azveb2bn7arhy79izk]]></nonce_str>

 <sign><![CDATA[2D8A96553672D56BB2908CE4B0A23D0F]]></sign>

</xml>

Copy after login

After submission, the return is correct, which contains perpay_id:

1

2

3

4

5

6

7

8

9

10

11

<xml>

 <return_code><![CDATA[SUCCESS]]></return_code>

 <return_msg><![CDATA[OK]]></return_msg>

 <appid><![CDATA[wx8888888888888888]]></appid>

 <mch_id><![CDATA[10012345]]></mch_id>

 <nonce_str><![CDATA[Be8YX7gjCdtCT7cr]]></nonce_str>

 <sign><![CDATA[885B6D84635AE6C020EF753A00C8EEDB]]></sign>

 <result_code><![CDATA[SUCCESS]]></result_code>

 <prepay_id><![CDATA[wx201410272009395522657a690389285100]]></prepay_id>

 <trade_type><![CDATA[JSAPI]]></trade_type>

</xml>

Copy after login

The js used to generate payment:

1

2

3

4

5

6

7

8

{

  "appId": "wx8888888888888888",

  "timeStamp": "1414411784",

  "nonceStr": "gbwr71b5no6q6ne18c8up1u7l7he2y75",

  "package": "prepay_id=wx201410272009395522657a690389285100",

  "signType": "MD5",

  "paySign": "9C6747193720F851EB876299D59F6C7D"

}

Copy after login

Notification xml returned after successful payment:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<xml><appid><![CDATA[wx8888888888]]></appid>

<bank_type><![CDATA[CCB_DEBIT]]></bank_type>

<fee_type><![CDATA[CNY]]></fee_type>

<is_subscribe><![CDATA[Y]]></is_subscribe>

<mch_id><![CDATA[1011111]]></mch_id>

<nonce_str><![CDATA[38gt0ffgsvfsdfsdfbt1981duv63p7]]></nonce_str>

<openid><![CDATA[o4p3SjfdsfdsfdsdCE5Y2XHw4]]></openid>

<out_trade_no><![CDATA[wx4b56d1fsdfdsf416643247]]></out_trade_no>

<result_code><![CDATA[SUCCESS]]></result_code>

<return_code><![CDATA[SUCCESS]]></return_code>

<sign><![CDATA[356EfsdfdsfsdsfE69509EDA344]]></sign>

<sub_mch_id><![CDATA[10018826]]></sub_mch_id>

<time_end><![CDATA[20141122160122]]></time_end>

<total_fee>1</total_fee>

<trade_type><![CDATA[JSAPI]]></trade_type>

<transaction_id><![CDATA[100715001020fsdfsd1220006123174]]></transaction_id>

</xml>

Copy after login

Summary: The above is the entire content of this article, I hope it can be helpful to everyone Learning helps.

Related recommendations:

phpSimple way to calculate age

phpCustomized time conversion function

phpInterface technology examples and graphic details

The above is the detailed content of How to write WeChat payment interface development program in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles