search
HomeBackend DevelopmentPHP TutorialHow to write WeChat payment interface development program in PHP

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

//使用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();
  }

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

$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);

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

// 打印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);
  }

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

$jsApi->setPrepayId($prepay_id);
 
$jsApiParameters = $jsApi->getParameters();

——————-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

<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>

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

<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>

The js used to generate payment:

{
  "appId": "wx8888888888888888",
  "timeStamp": "1414411784",
  "nonceStr": "gbwr71b5no6q6ne18c8up1u7l7he2y75",
  "package": "prepay_id=wx201410272009395522657a690389285100",
  "signType": "MD5",
  "paySign": "9C6747193720F851EB876299D59F6C7D"
}

Notification xml returned after successful payment:

<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>

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
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
PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.