PHP WeChat payment development method of callback after scanning payment (mode 2)

高洛峰
Release: 2017-03-09 15:40:37
Original
3458 people have browsed it

In fact, when I wrote this article, I felt that I was already behind the times. However, when I searched for "WeChat payment development - how to call back after scanning payment (mode 2)" on Baidu to find the answer, I found that many friends still did not solve this problem. problem, so I will share my solution ideas with everyone.

1. Download the WeChat payment SDK (the author uses PHP development as an example, the sdk package is WxpayAPI_php_v3.zip)

After downloading the SDK package, unzip it. In the unzipped directory, we will see the following Directory

PHP WeChat payment development method of callback after scanning payment (mode 2)

2. After consulting the WeChat payment developer documentation, we learned that the demo of WeChat scan code payment is the native.php file in the example directory

For convenience, what we have to do is to put the entire decompressed file into the wxpay (can be named according to personal preference) folder in the root directory of the local environment

3. Taking the author as an example, when browsing Enter http://localhost/wxpay/example/native.php

into the browser. After opening the above URL, we found that there are two QR codes. As the title says, what we are studying today is the mode two scan code (also recommended by the official Mode 2 scan code to pay)

4. We log in to WeChat with our mobile phone, scan the QR code of Mode 2 on the page above, and pay

Here we find an interesting problem, when After your payment is successful, there are no changes in the PC page, so the main issue we consider is how to call back after payment.

I won’t talk too much nonsense here. The author referred to many methods on the Internet and summarized them as follows:

1. Delete the scan code mode 1 in the native.php file. Some html, only some related html codes in scan code mode 2 are left.

2. As the official document also states that the payment result of scan code mode 2 is an asynchronous response and will not actively return the payment result, so we use javascript to monitor the payment result from time to time, and then based on the request result , making the next page callback. The author’s final code is as follows, interested friends can refer to it:

native.php file

<?php
ini_set(&#39;date.timezone&#39;,&#39;Asia/Shanghai&#39;);
//error_reporting(E_ERROR);

require_once "../lib/WxPay.Api.php";
require_once "WxPay.NativePay.php";
require_once &#39;log.php&#39;;

//模式一
/**
 * 流程:
 * 1、组装包含支付信息的url,生成二维码
 * 2、用户扫描二维码,进行支付
 * 3、确定支付之后,微信服务器会回调预先配置的回调地址,在【微信开放平台-微信支付-支付配置】中进行配置
 * 4、在接到回调通知之后,用户进行统一下单支付,并返回支付信息以完成支付(见:native_notify.php)
 * 5、支付完成之后,微信服务器会通知支付成功
 * 6、在支付成功通知中需要查单确认是否真正支付成功(见:notify.php)
 */
$notify = new NativePay();
$url1 = $notify->GetPrePayUrl("123456789");

//模式二
/**
 * 流程:
 * 1、调用统一下单,取得code_url,生成二维码
 * 2、用户扫描二维码,进行支付
 * 3、支付完成之后,微信服务器会通知支付成功
 * 4、在支付成功通知中需要查单确认是否真正支付成功(见:notify.php)
 */
$input = new WxPayUnifiedOrder();
$input->SetBody("1分钱购买何宁");
$input->SetAttach("1分钱购买何宁");
$num=WxPayConfig::MCHID.date("YmdHis");
$input->SetOut_trade_no($num);
$input->SetTotal_fee("1");
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("test");
$input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
$input->SetTrade_type("NATIVE");
$input->SetProduct_id("123456789");
$result = $notify->GetPayUrl($input);
$url2 = $result["code_url"];
?>

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1" /> 
    <title>微信支付样例</title>
</head>
<body>
    <div style="margin-left: 10px;color:#556B2F;font-size:30px;font-weight: bolder;">扫描支付模式二</div><br/>
    <img alt="模式二扫码支付" src="qrcode.php?data=<?php echo urlencode($url2);?>"   style="max-width:90%"/>
    <div id="myDiv"></div><div id="timer">0</div>
    <script>  
    //设置每隔1000毫秒执行一次load() 方法  
    var myIntval=setInterval(function(){load()},1000);  
    function load(){  
       document.getElementById("timer").innerHTML=parseInt(document.getElementById("timer").innerHTML)+1; 
        var xmlhttp;    
        if (window.XMLHttpRequest){    
            // code for IE7+, Firefox, Chrome, Opera, Safari    
            xmlhttp=new XMLHttpRequest();    
        }else{    
            // code for IE6, IE5    
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");    
        }    
        xmlhttp.onreadystatechange=function(){    
            if (xmlhttp.readyState==4 && xmlhttp.status==200){    
                trade_state=xmlhttp.responseText;  
                if(trade_state==&#39;SUCCESS&#39;){  
                    document.getElementById("myDiv").innerHTML=&#39;支付成功&#39;;  
                    //alert(transaction_id);  
                    //延迟3000毫秒执行tz() 方法
                    clearInterval(myIntval);  
                    setTimeout("location.href=&#39;success.php&#39;",3000);  

                }else if(trade_state==&#39;REFUND&#39;){  
                    document.getElementById("myDiv").innerHTML=&#39;转入退款&#39;; 
                    clearInterval(myIntval); 
                }else if(trade_state==&#39;NOTPAY&#39;){  
                    document.getElementById("myDiv").innerHTML=&#39;请扫码支付&#39;;  
                      
                }else if(trade_state==&#39;CLOSED&#39;){  
                    document.getElementById("myDiv").innerHTML=&#39;已关闭&#39;;  
                    clearInterval(myIntval);
                }else if(trade_state==&#39;REVOKED&#39;){  
                    document.getElementById("myDiv").innerHTML=&#39;已撤销&#39;;  
                    clearInterval(myIntval);
                }else if(trade_state==&#39;USERPAYING&#39;){  
                    document.getElementById("myDiv").innerHTML=&#39;用户支付中&#39;;  
                }else if(trade_state==&#39;PAYERROR&#39;){  
                    document.getElementById("myDiv").innerHTML=&#39;支付失败&#39;; 
                    clearInterval(myIntval); 
                }  
                 
            }    
        }    
        //orderquery.php 文件返回订单状态,通过订单状态确定支付状态  
        xmlhttp.open("POST","orderquery.php",false);    
        //下面这句话必须有    
        //把标签/值对添加到要发送的头文件。    
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");    
        xmlhttp.send("out_trade_no=<?php echo $num;?>");  
         
        }  
    </script>
    
</body>
</html>
Copy after login

## The #orderquery.php code has also been adjusted accordingly:

<?php
ini_set(&#39;date.timezone&#39;,&#39;Asia/Shanghai&#39;);
error_reporting(E_ERROR);
require_once "../lib/WxPay.Api.php";
require_once &#39;log.php&#39;;
 
//初始化日志
$logHandler= new CLogFileHandler("./logs/".date(&#39;Y-m-d&#39;).&#39;.log&#39;);
$log = Log::Init($logHandler, 15);
 
function printf_info($data)
{
    foreach($data as $key=>$value){
        echo "<font color=&#39;#f00;&#39;>$key</font> : $value <br/>";
    }
}
 
 
if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
    $transaction_id = $_REQUEST["transaction_id"];
    $input = new WxPayOrderQuery();
    $input->SetTransaction_id($transaction_id);
    //printf_info(WxPayApi::orderQuery($input));
    $result=WxPayApi::orderQuery($input);
    echo $result[&#39;trade_state&#39;];
    exit();
}
 
if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
    $out_trade_no = $_REQUEST["out_trade_no"];
    $input = new WxPayOrderQuery();
    $input->SetOut_trade_no($out_trade_no);
    //printf_info(WxPayApi::orderQuery($input));
    $result=WxPayApi::orderQuery($input);
    echo $result[&#39;trade_state&#39;];
    exit();
}
?>
Copy after login

##New success.php file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>微信支付成功</title>
</head>
 
<body>
<br /><br /><br /><br /><br /><br /><br />
<h1>微信支付成功</h1>
</body>
</html>
Copy after login

The above is the code summarized by the author. After debugging, it was found that there is no problem. Interested friends can refer to it.

The above is the detailed content of PHP WeChat payment development method of callback after scanning payment (mode 2). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!