Table of Contents
2. Merchant platform settings
3. Use the official V3.7 sample code
4. Example of using official V3 Code
Home WeChat Applet WeChat Development WeChat payment for WeChat development

WeChat payment for WeChat development

May 27, 2017 pm 01:31 PM
WeChat development pay

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

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

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

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

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

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

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

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

How to pay for a taxi ride on Baidu Maps. Introduction to the payment steps for a taxi ride. How to pay for a taxi ride on Baidu Maps. Introduction to the payment steps for a taxi ride. Mar 13, 2024 am 10:04 AM

Baidu Map APP has now become the preferred travel navigation software for many users, so some of the functions here are comprehensive and can be selected and operated for free to solve some of the problems that you may encounter in daily travel. You can all check some of your own travel routes and plan some of your own travel plans. After checking the corresponding routes, you can choose appropriate travel methods according to your own needs. So whether you choose some public transportation, Cycling, walking or taking a taxi can all satisfy your needs. There are corresponding navigation routes that can successfully lead you to a certain place. Then everyone will feel more convenient if they choose to take a taxi. There are many drivers They are all able to take orders online, and taxi-hailing has become super

How uniapp application implements payment and order management How uniapp application implements payment and order management Oct 19, 2023 am 10:37 AM

uniapp is a cross-platform application development framework that can develop small programs, Apps and H5 at the same time. In uniapp applications, payment and order management are very common needs. This article will introduce how to implement payment functions and order management in the uniapp application, and give specific code examples. 1. Implementing the payment function The payment function is the key to realizing online transactions, and it usually requires integrating the SDK of a third-party payment platform. The following are the specific steps to implement the payment function in uniapp: Register and obtain a third-party payment platform

Pay using PHP and PayPal API Pay using PHP and PayPal API Jun 19, 2023 pm 04:13 PM

With the increasing popularity of online transactions, payment methods are gradually diversifying, among which PayPal is very popular as a widely used payment method. If you want to use PayPal to process transactions on your website or application, then you can use PHP and PayPal API to complete the payment process easily. PayPalAPI is a set of programming interfaces for interacting with PayPal. Through the API, you can receive notifications from PayPal, query the latest transaction information, and initiate payments.

How to pay for taking the bus in Wuhan How to pay for taking the bus in Wuhan Oct 13, 2022 pm 02:17 PM

Payment methods for taking buses in Wuhan: 1. For cash payment, you need to prepare sufficient change in advance and put the money directly into the coin slot; 2. Swipe the Wuhan Tong card. The full name of Wuhan Tong is Wuhan City Card, which is an integrated circuit Card, also known as chip card; 3. Alipay electronic bus card, first get a Wuhan electronic bus card in Alipay, and then directly scan the QR code to deduct the money when getting on the bus; 4. WeChat bus code payment , open the WeChat "Ride Code" applet, activate the Wuhan "Ride Code", and you can directly scan the QR code to deduct payment and get on the bus.

How to close Meituan Takeout Express Payment How to close Meituan Takeout Express Payment Mar 27, 2024 am 10:41 AM

In the fast-paced modern life, Meituan Takeaway is deeply loved by consumers for its convenient services and rich choices. Among them, the ultra-fast payment function brings great convenience to users. Payment can be completed with one click, eliminating tedious input steps. However, many users don't like paying directly without confirmation, so they want to turn off this feature. So how to turn off the fast payment of Meituan Waimai? In the following, the editor of this website will bring you a detailed step-by-step setup tutorial, I hope it can help you! 1. Click the &quot;Meituan Takeout&quot; shortcut icon on the mobile phone desktop. 2. Log in to the Meituan takeout app on your mobile phone and click &quot;My&quot; in the lower right corner. 3. In the My interface, click &quot;Enter Wallet&quot;. 4. On the Meituan Wallet interface, click the &quot;Settings&quot; icon in the upper right corner

What does paynow payment mean? What does paynow payment mean? Sep 30, 2022 am 11:01 AM

PayNow payment is an electronic transfer service. Users can directly initiate real-time SGD transfers to the payee through the mobile phone number, ID card/FIN number, UEN number or PayNow QR code specified by the payee without the need for the other party. Bank account information.

Establish an order payment table for the grocery shopping system in MySQL Establish an order payment table for the grocery shopping system in MySQL Nov 01, 2023 pm 03:48 PM

To establish the order payment table of the grocery shopping system in MySQL, specific code examples are required. With the development of the Internet, shopping has become more and more convenient. In the shopping process, order payment is an important part of the shopping process. The grocery shopping system not only needs to have an order generation function, but also must have a complete payment process, because only successful payment can be regarded as completing a transaction. This article will describe how to create an order payment table for the grocery shopping system in MySQL and provide specific code examples. 1. Design of order payment table. The order payment table in the grocery shopping system stores orders.

Where can Meituan instant discount be deducted by default when payment is enabled_ Tutorial on Meituan instant discount being deducted by default when payment is enabled Where can Meituan instant discount be deducted by default when payment is enabled_ Tutorial on Meituan instant discount being deducted by default when payment is enabled Mar 28, 2024 am 11:00 AM

1. First open the [Meituan] APP, click the [My] button in the bottom navigation bar. 2. Then click the [My Wallet] function button and click the [Cash Voucher] button. 3. Then in the top function bar, click the [Instant Deduction] button, and click the switch button to turn on [Default Deduction during Payment] to successfully turn it on.

See all articles