


Keywords: WeChat payment WeChat payment v3 jsapi payment unified payment Native payment prepay_id
This article introduces the jsapi implementation process under WeChat payment
Preface
WeChat Payment is now divided into v2 version and v3 version. Those who applied before September 10, 2014 will be in v2 version, and those who applied after that will be in v3 version. The V3 version of WeChat Pay does not have the paySignKey parameter. For related introduction to v2, please refer to other articles of Fangbei Studio. This article introduces WeChat Pay v3.
Process Implementation
1. OAuth2.0 Authorization
JSAPI needs to call the login authorization interface to obtain the user's Openid before payment. Therefore, authorization needs to be done once, and the confirmation box will not pop up for this authorization.
The essence is to jump to
http://www.fangbei.org/wxpay/js_api_call.php
when the user accesses
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8888888888888888&redirect_uri=http://www.fangbei.org/wxpay/js_api_call.php&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
to obtain the code parameter, and obtain authorization access_token and openid based on the code
For the detailed implementation process, please refer to WeChat Public Platform Development (71) OAuth2.0 Web Authorization
In the Demo of WeChat Pay, the code is
1 //使用jsapi接口 2 $jsApi = new JsApi_pub(); 3 4 //=========步驟1:網(wǎng)頁(yè)授權(quán)獲取用戶openid============ 5 //通過(guò)code獲得openid 6 if (!isset($_GET['code'])) 7 { 8 //觸發(fā)微信返回code碼 9 $url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL);10 Header("Location: $url"); 11 }else12 {13 //獲取code碼,以獲取openid14 $code = $_GET['code'];15 $jsApi->setCode($code);16 $openid = $jsApi->getOpenId();17 }
The final result of this step is to obtain the current User's openid
ou9dHt0L8qFLI1foP-kj5x1mDWsM
2. Unified payment
Unified payment is an interface that generates payment orders and returns pre-payment order numbers in various JSAPI/NATIVE/APP payment scenarios. Currently, all scenarios of WeChat payment are All use this interface
In unified payment, the following parameters are obtained from the configuration, or automatically generated by the class, and do not need to be filled in by the user
$this->parameters["appid"] = WxPayConf_pub::APPID;//公眾賬號(hào)ID$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//商戶號(hào)$this->parameters["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];//終端ip $this->parameters["nonce_str"] = $this->createNoncestr();//隨機(jī)字符串$this->parameters["sign"] = $this->getSign($this->parameters);//簽名
In JSAPI payment, fill in the following parameters in addition
//統(tǒng)一支付接口中,trade_type為JSAPI時(shí),openid為必填參數(shù)!$unifiedOrder->setParameter("openid","$openid");//商品描述$unifiedOrder->setParameter("body","方倍工作室");//商品描述 //自定義訂單號(hào),此處僅作舉例$timeStamp = time();$out_trade_no = WxPayConf_pub::APPID."$timeStamp";$unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商戶訂單號(hào) $unifiedOrder->setParameter("total_fee","1");//總金額$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//通知地址 $unifiedOrder->setParameter("trade_type","JSAPI");//交易類型
Others are optional parameters
//非必填參數(shù),商戶可根據(jù)實(shí)際情況選填 //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商戶號(hào) //$unifiedOrder->setParameter("device_info","XXXX");//設(shè)備號(hào) //$unifiedOrder->setParameter("attach","XXXX");//附加數(shù)據(jù) //$unifiedOrder->setParameter("time_start","XXXX");//交易起始時(shí)間 //$unifiedOrder->setParameter("time_expire","XXXX");//交易結(jié)束時(shí)間 //$unifiedOrder->setParameter("goods_tag","XXXX");//商品標(biāo)記 //$unifiedOrder->setParameter("openid","XXXX");//用戶標(biāo)識(shí) //$unifiedOrder->setParameter("product_id","XXXX");//商品ID
These parameters eventually form such xml data,
<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://www.fangbei.org/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>
Submit these data to the unified payment interface
https://api.mch.weixin.qq.com/pay/unifiedorder
will return the following data
<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>
It contains the most important prepayment ID parameter, prepay_id, with a value of
wx201410272009395522657a690389285100
3. JS API payment
After the previous preparations are completed, JS API generates jsapi payment parameters based on prepay_id
The generated code is as follows
//=========步驟3:使用jsapi調(diào)起支付============$jsApi->setPrepayId($prepay_id);$jsApiParameters = $jsApi->getParameters();
The generated json data is as follows
{ "appId": "wx8888888888888888", "timeStamp": "1414411784", "nonceStr": "gbwr71b5no6q6ne18c8up1u7l7he2y75", "package": "prepay_id=wx201410272009395522657a690389285100", "signType": "MD5", "paySign": "9C6747193720F851EB876299D59F6C7D" }
Debug the js interface in the WeChat browser, the code is as follows
<html><head> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> <title>微信安全支付</title> <script type="text/javascript"> //調(diào)用微信JS api 支付 function jsApiCall() { WeixinJSBridge.invoke( 'getBrandWCPayRequest', <?php echo $jsApiParameters; ?>, function(res){ WeixinJSBridge.log(res.err_msg); //alert(res.err_code+res.err_desc+res.err_msg); } ); } function callpay() { if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } }else{ jsApiCall(); } } </script></head><body> </br></br></br></br> <p align="center"> <button style="width:210px; height:30px; background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" >貢獻(xiàn)一下</button> </p></body></html>
When the user clicks the "Contribute" button, the WeChat payment plug-in will pop up and the user can start payment.
4. Payment notification
After the payment is successful, the notification interface will also receive an xml notification of successful payment.
<xml> <appid><![CDATA[wx8888888888888888]]></appid> <bank_type><![CDATA[CFT]]></bank_type> <fee_type><![CDATA[CNY]]></fee_type> <is_subscribe><![CDATA[Y]]></is_subscribe> <mch_id><![CDATA[10012345]]></mch_id> <nonce_str><![CDATA[60uf9sh6nmppr9azveb2bn7arhy79izk]]></nonce_str> <openid><![CDATA[ou9dHt0L8qFLI1foP-kj5x1mDWsM]]></openid> <out_trade_no><![CDATA[wx88888888888888881414411779]]></out_trade_no> <result_code><![CDATA[SUCCESS]]></result_code> <return_code><![CDATA[SUCCESS]]></return_code> <sign><![CDATA[0C1D7F2534F1473247550A5A138F0CEB]]></sign> <sub_mch_id><![CDATA[10012345]]></sub_mch_id> <time_end><![CDATA[20141027200958]]></time_end> <total_fee>1</total_fee> <trade_type><![CDATA[JSAPI]]></trade_type> <transaction_id><![CDATA[1002750185201410270005514026]]></transaction_id> </xml>
After notification_url is received, a confirmation success message will be returned to WeChat server
<xml> <return_code><![CDATA[SUCCESS]]></return_code></xml>
The above is the detailed content of Detailed explanation of JS API payment examples developed by WeChat. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

H5 is more flexible and customizable, but requires skilled technology; mini programs are quick to get started and easy to maintain, but are limited by the WeChat framework.

Binance C2C transactions allow users to buy and sell cryptocurrencies directly, and pay attention to the risks of counterparty, payment and price fluctuations. Choosing high-credit users and secure payment methods can reduce risks.

According to news from this site on August 2, WeChatPayMY (Note from this site: WeChat Pay Malay Wallet) announced that it will stop the registration of new e-wallet users from August 1, 2024, and will stop registration of new e-wallet users on September 1, 2024. The payment service will be stopped from that date. WeChat Pay Malaysia Business Adjustment Announcement 1. Business adjustment: WeChatPayMY has stopped new user registration on August 1, 2024. 2. Existing users with balances can withdraw funds through existing services. WeChat Pay stated that users can still withdraw cash from their e-wallets before December 31, 2024, but users can still choose special withdrawal arrangements after January 1, 2025. In addition to this, WeChat’s existing messaging services and other features on the platform (such as WeChat payment

Detailed explanation of DeepSeekAPI access and call: Quick Start Guide This article will guide you in detail how to access and call DeepSeekAPI, helping you easily use powerful AI models. Step 1: Get the API key to access the DeepSeek official website and click on the "Open Platform" in the upper right corner. You will get a certain number of free tokens (used to measure API usage). In the menu on the left, click "APIKeys" and then click "Create APIkey". Name your APIkey (for example, "test") and copy the generated key right away. Be sure to save this key properly, as it will only be displayed once

According to news on September 2, this afternoon, the Weibo topic "Apple WeChat" topped the hot search list, triggering heated discussions. On this topic, many netizens support WeChat. The reason is that one is a tool and the other is social. WeChat currently has no substitute, and other social software cannot replace it, and Apple has a lot of substitutes for each other. It is understood that the differences between Apple and WeChat stem from the "Apple tax". Under the current iOS ecosystem, the in-app purchase revenue generated from mini-games in WeChat and Douyin is not connected to Apple’s own payment channels. For this reason, Apple requires WeChat and Douyin to fix the "loophole" that allows in-app mini-game purchases to switch to external payments, allowing Apple to gain a share of the revenue. Like all manufacturers, in Apple's eyes, the commission for IAP (in-app purchase) applications is

According to news from this website on June 27, Tencent Public Relations Director Zhang Jun said that WeChat PayHK further expanded the mainland’s transportation scene yesterday, achieving full coverage of the public transportation network in Beijing, Shanghai, Guangzhou and Shenzhen. According to reports, the new cities include Beijing, Huizhou, Jiangmen, Qingyuan, Shaoguan, Heyuan, Shantou, Shanwei, Jieyang, Lijiang, Quanzhou, Ningbo, Suzhou, etc. Currently, 30 cities support scanning QR codes to ride. According to reports, through the "Cross-Border Travel" section of WeChat Hong Kong Wallet, users can choose to open a bus or subway code in the corresponding city, and conveniently scan the code to take the bus without queuing to buy tickets, and the fare will be settled at a preferential exchange rate. Note on this site: Users register WeChat or WeChat through a Hong Kong mobile phone number and open a WeChat payment Hong Kong dollar wallet (WeChatPa

For high-performance PHP API development, the choice of the best framework depends on the target API type, expected load and available resources. Laravel has a fast routing system, a powerful caching mechanism, and a built-in event system, while Symfony has a modular architecture, high-performance HTTP benchmarks, and a built-in event scheduler. ZendFramework provides high-speed routing, an integrated caching framework, and ready-to-use benchmarking tools.

OKX: The top three trading volumes in the world, supports 620 trading pairs, and is certified for security, suitable for high-frequency traders. Binance: The world's largest platform, with an average daily transaction volume of over US$19 billion and a user of over 150 million, supporting multilingual and localized payments. Gate.io: Attract long-tail currency investors with 1400 trading pairs and low fees, the first "wealth management" pledge mining is to be pledged and mining, with annualized returns up to 15%. Kraken: The first choice for European and American institutions, passing SEC and EU MiCA certification, zero major vulnerabilities, and military-level encryption technology to ensure transaction security. Coinbase: US compliance benchmark, simple interface, provides a tutorial on "learning to earn coins", and listed companies have custodial assets of over US$45 billion. Huo
