Home  >  Article  >  WeChat Applet  >  WeChat payment for WeChat development

WeChat payment for WeChat development

零下一度
零下一度Original
2017-05-27 13:31:172562browse

1. WeChat background settings

1. Add test authorization directory and test whitelist:

In the WeChat background, Set the test authorization directory, such as xxx.sinaapp.com/example/, and add your WeChat ID to the test whitelist.
Note that the "personal WeChat ID" here is neither a QQ account nor a personal nickname. It is the string in the "WeChat ID" field in the "Me" interface after logging in to WeChat.
It doesn’t matter if the payment authorization directory is set or not, because we are just testing.

2. List content

Set the web page authorization domain name:
Set in "Developer Center/Interface Permission Table/Web Page Account/Web Page Authorization to Obtain User Basic Information". The webpage authorized domain name is set to the domain name of the test server, such as: xxx.sinaapp.com, http:// is not required.

2. Merchant platform settings

1. Download certificate

Download in "Account Settings/API Security/API Certificate". The administrator’s mobile phone verification code is required. After downloading and decompressing, we need to use apiclient_key.pem and apiclient_cert.pem.

2. Generate payment key

Set in "Account Settings/API Security/API Key". The payment key will be used during payment. This value is the KEY constant in the source code configuration file.

3. Use the official V3.7 sample code

1. Modify the configuration in Wxpay.pub.config.php, mainly:

    const APPID                 //公众号中“开发者中心”看到的AppID
    const MCHID                     //微信支付商户资料审核成功邮件中的商户号
    const KEY                   //你在商户平台中设置的支付key
    const APPSECRET             //公众号中“开发者中心”看到的AppSecret

    const JS_API_CALL_URL       //设置这个url,可在此页面中获得用户的openid。

    //证书路径,注意应该填写绝对路径
    const SSLCERT_PATH          // apiclient_cert.pem文件url
    const SSLKEY_PATH               // apiclient_key.pem文件url,如’/cert/ apiclient_key.pem’
    const NOTIFY_URL                //异步通知url,可使用demo中的notify_url.php

2. Modify the bug in the official code:
If the "curl_setopt() expects parameter 2 to be long" error occurs, it is because there are several places in WxPayPubHelper.php that misspell "curl_setopt" and spell it as "curl_setop" ”, just modify it. If "curl_close(): 11 is not a valid" appears, it is because a closed curl session was closed by mistake. You can add the following judgment to the curl_close() code:

if(gettype($ch) == 'resource') curl_close($ch);

3, official demo It doesn't work directly, we need to figure it out ourselves. First, add a link to index.php:

<a href="pay.php"> 获取openid</a></h4>

3. Then write a pay.php page to obtain the user's openid and initiate payment:

<?php
/**
 * JS_API支付demo
 * ====================================================
 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
 * 成功调起支付需要三个步骤:
 * 步骤1:网页授权获取用户openid
 * 步骤2:使用统一支付接口,获取prepay_id
 * 步骤3:使用jsapi调起支付
 */
include_once ("WxPayPubHelper.php");

$jsApi = new JsApi_pub();
// =========步骤1:网页授权获取用户openid============
// 通过code获得openid
if (! isset($_GET[&#39;code&#39;])) {
 // 触发微信返回code码
 $url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL);
 Header("Location: $url");
} else {
 // 获取code码,以获取openid
 $code = $_GET[&#39;code&#39;];
 $jsApi->setCode($code);
 $openid = $jsApi->getOpenId();
}

$goods = "test";
// 使用统一支付接口
$unifiedOrder = new UnifiedOrder_pub();
$unifiedOrder->setParameter("openid", "$openid"); // 用户openid
$unifiedOrder->setParameter("body", "$goods"); // 商品描述
 // 自定义订单号,此处仅作举例
$timeStamp = time();
$out_trade_no = WxPayConf_pub::APPID . "$timeStamp"; // 商户订单号
$unifiedOrder->setParameter("out_trade_no", "$out_trade_no");
$price = "1";
$unifiedOrder->setParameter("total_fee", "$price"); // 总金额
$unifiedOrder->setParameter("notify_url", WxPayConf_pub::NOTIFY_URL); // 通知地址
$unifiedOrder->setParameter("trade_type", "JSAPI"); // 交易类型

$prepay_id = $unifiedOrder->getPrepayId();
// =========步骤3:使用jsapi调起支付============
$jsApi->setPrepayId($prepay_id);

$jsApiParameters = $jsApi->getParameters();
echo $jsApiParameters;

?>

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<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>
    <p> </p>
    <p> </p>
    <p align="center">
        <table border="1">
            <tr>
                <td>openID</td>
                <td><?php echo $openid;?></td>
            </tr>
            <tr>
                <td>商品名称</td>
                <td><?php echo $goods;?></td>
            </tr>
            <tr>
                <td>订单号</td>
                <td><?php echo $out_trade_no;?></td>
            </tr>
            <tr>
                <td>prepay_id</td>
                <td><?php echo $prepay_id;?></td>
            </tr>
            <tr>
                <td>价格</td>
                <td><?php echo $price;?></td>
            </tr>
        </table>
        <button data-theme="b" type="button" onclick="callpay()">贡献一下</button>
    </p>
</body>
</html>

4. Example of using official V3 Code

1. Download the official sample code
The latest SDK version is V3.7, but instead of downloading the V3.7 demo (that example won’t work), we should download the V3 example:

pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1

2. Unzip the demo and put it in your web root directory. For example, the directory after unzipping the compressed package is WxpayAPI_php_v3. You need to enter this directory, select all the files, and then copy them to your project directory. There is an index.php in this directory, so you need to access xxx.sinaapp.com/index.php when testing.

3. Change the url address of the tag in index.php to the url address on your server.

4. In your WeChat, open a dialogue window, enter the index.php address, such as xxx.sinaapp.com/index.php, and then click this link in the dialogue window. Several buttons will appear. Click the "JSAPI Payment" button, and a window with a payment amount of 1 cent will pop up. Enter the consignee and pay. The payment success interface will pop up.
At this step, it means that the official payment code is basically available. Next, we can modify it into our own code based on it.

5. Replace apiclient_key.pem and apiclient_cert.pem in the cert directory with your own certificate.

6. Modify the following items in WxPay.Config.php to be your own:

const APPID                 //公众号中“开发者中心”看到的AppID
const MCHID                     //微信支付商户资料审核成功邮件中的商户号
const KEY                   //你在商户平台中设置的支付key
const APPSECRET             //公众号中“开发者中心”看到的AppSecret

7. Because we use Sina's sae as the test server, sae does not allow direct writing of files. io, so the file operations in the official website code can be modified accordingly (using SaeStorage). That is to say, the CLogFileHandler class in log.php needs to be modified:

class CLogFileHandler implements ILogHandler
{
    private $fn=null;
    private $ss=null;
    public function construct($file = &#39;&#39;)
 {
        $this->fn=str_replace("../logs/", "", $file);
        $this->ss=new SaeStorage();
    }
    public function write($msg)
 {
        $bytes = $this->ss->read(&#39;log&#39;, $this->fn);
        $str = $bytes;
        $this->ss->write(&#39;log&#39;, $this->fn, "$str\n$msg");
    }
    public function destruct()
 {
        $fn=null;
        $ss=null;
    }
}

8. If an error of signature failure occurs, we can use WeChat’s payment interface debugging tool to test: pay.weixin.qq.com/wiki /tools/signverify/.
Although this tool is used to verify "scanned payment", through its "Add Parameter" button and "Delete Parameter" button, we can also use it to test "Official Account Payment". For example, if the xml content you submitted is as follows (you can use the Log function to save the submitted xml content to sae storage, and then download the log file):

<xml><openid><![CDATA[om8888LTHBj99992Qgl_eUAOFgxs]]></openid><body><![CDATA[test]]></body><out_trade_no><![CDATA[wx111196222243ffa1143858aaaa]]></out_trade_no><total_fee>1</total_fee><notify_url><![CDATA[http://xxx.sinaapp.com/wxpay/demo/notify_url.php]]></notify_url><trade_type><![CDATA[JSAPI]]></trade_type><appid><![CDATA[wx000096104a431111]]></appid><mch_id>6666833333</mch_id><spbill_create_ip><![CDATA[10.211.76.107]]></spbill_create_ip><nonce_str><![CDATA[1agieoxyi8hc7e817rsnjlyn9lxmsnxj]]></nonce_str><sign><![CDATA[817034E4DE8E6067EB85CDF7318EF0A1]]></sign></xml>

, then you can fill in the form in the test tool like this:
WeChat payment for WeChat development
Click "Generate Signature". Compare the obtained signature with the signature in the log file to see if they are consistent, and you can eliminate problems with the signature algorithm.
If the two signatures are consistent, it is definitely a problem with the payment key. Either the product MM made a mistake, or the AppSecret and payment key were reversed (once the product MM told me to use a wrong payment key, which wasted 3 days of my time! I repeatedly confirmed every code, every time After setting the background parameters, I finally used the "Payment Interface Debugging Tool" to confirm that the signature was correct. The problem was the payment key, so I logged into the merchant platform. Since I was not the administrator, I asked the product MM for the mobile phone verification code and reset the payment key. , the code will work in one click)

[Related recommendations]

1. WeChat public account platform source code download

2. Share the example tutorial of credit card payment in the development of WeChat official account

3. Detailed explanation of the credit card payment example of WeChat payment development

4 . Detailed explanation of WeChat applet payment function development error summary

The above is the detailed content of WeChat payment for WeChat development. 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