Detailed explanation of JS API payment examples developed by WeChat

Y2J
Release: 2017-05-03 11:08:38
Original
2084 people have browsed it

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
Copy after login

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
Copy after login

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:网页授权获取用户openid============ 5 //通过code获得openid 6 if (!isset($_GET['code'])) 7 { 8     //触发微信返回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 }
Copy after login

The final result of this step is to obtain the current User's openid

ou9dHt0L8qFLI1foP-kj5x1mDWsM
Copy after login

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;//公众账号ID$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//商户号$this->parameters["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];//终端ip        $this->parameters["nonce_str"] = $this->createNoncestr();//随机字符串$this->parameters["sign"] = $this->getSign($this->parameters);//签名
Copy after login

In JSAPI payment, fill in the following parameters in addition

//统一支付接口中,trade_type为JSAPI时,openid为必填参数!$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");//交易类型
Copy after login

Others are optional parameters

//非必填参数,商户可根据实际情况选填
//$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
Copy after login

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>
Copy after login

Submit these data to the unified payment interface

https://api.mch.weixin.qq.com/pay/unifiedorder
Copy after login

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>
Copy after login

It contains the most important prepayment ID parameter, prepay_id, with a value of

wx201410272009395522657a690389285100
Copy after login

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调起支付============$jsApi->setPrepayId($prepay_id);$jsApiParameters = $jsApi->getParameters();
Copy after login

The generated json data is as follows

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

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">
        //调用微信JS api 支付
        function jsApiCall()
        {
            WeixinJSBridge.invoke(                &#39;getBrandWCPayRequest&#39;,                <?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(&#39;WeixinJSBridgeReady&#39;, jsApiCall, false);
                }else if (document.attachEvent){
                    document.attachEvent(&#39;WeixinJSBridgeReady&#39;, jsApiCall); 
                    document.attachEvent(&#39;onWeixinJSBridgeReady&#39;, 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()" >贡献一下</button>
    </p></body></html>
Copy after login

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>
Copy after login

After notification_url is received, a confirmation success message will be returned to WeChat server

<xml>
  <return_code><![CDATA[SUCCESS]]></return_code></xml>
Copy after login

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template