thinkphp3.2.3 WeChat PC scan code payment mode two

This article mainly introduces the scan code payment scenario two.

There are currently two modes, mode one is slightly more complicated than mode two. As for the specific content, process, and WeChat development documents of mode one and mode two, there are detailed introductions, so I won't talk nonsense here, and then hurry up and follow the tutorial!

Download SDK files

Wxpay Library

And put several files under SDK file/lib to / ThinkPHP /Library/Vendor/

Modify the configuration options in WxPay.pub.config.php

  1. //=======【基本信息设置】=====================================

  2. //微信公众号身份的唯一标识。审核通过后,在微信发送的邮件中查看

  3. const APPID = '公众号表示ID';

  4. //受理商ID,身份标识

  5. const MCHID = '商户ID';

  6. //商户支付密钥Key。审核通过后,在微信发送的邮件中查看

  7. const KEY = 'KEY密匙';

  8. //JSAPI接口中获取openid,审核后在公众平台开启开发模式后可查看

  9. const APPSECRET = 'SECRET密匙';

  10.  
  11. //=======【JSAPI路径设置】===================================

  12. //获取access_token过程中的跳转uri,通过跳转将code传入jsapi支付页面

  13. const JS_API_CALL_URL = 'http://www.laoji.org';

  14.  
  15. //=======【证书路径设置】=====================================

  16. //证书路径,注意应该填写绝对路径

  17. const SSLCERT_PATH = "__ROOT__\paypem\\apiclient_cert.pem";

  18. const SSLKEY_PATH = "__ROOT__\paypem\\apiclient_key.pem";

  19.  
  20. //=======【异步通知url设置】===================================

  21. //异步通知url,商户根据实际开发过程设定

  22. const NOTIFY_URL = 'http://www.laoji.org/wxpay/notify';

  23.  
  24. //=======【curl超时设置】===================================

  25. //本例程通过curl使用HTTP POST方法,此处可修改其超时时间,默认为30秒

  26. const CURL_TIMEOUT = 30;

New controller method of WeChat

    /*
     * WeChat Pay
     */
    public function wxPay()
    {         $order_num = retailOrderNum(3);//Order number         $money = $account * 100;//Amount is in points         //Introduction of the class file         vendor('WxPcpay.WxPayPubHelper' );         vendor('phpqrcode.phpqrcode');//Introduce         //Use unified payment interface         $unifiedOrder = new \UnifiedOrder_pub();         //Set unified payment interface parameters         //Set required parameters         $unifiedOrder->setParameter("body ",'Supplier recharge');//Product description         //Custom order number, here is just an example         $timeStamp = time();         $unifiedOrder->setParameter("out_trade_no", $order_num);//Merchant order No.         $unifiedOrder->setParameter("total_fee", 1);//Total amount














        $unifiedOrder->setParameter("time_start", date("YmdHis"));//Trading start time
        $unifiedOrder->setParameter("time_expire", date("YmdHis", time() + 7200));// Transaction end time
        $unifiedOrder->setParameter("notify_url",'');//Notification address
        $unifiedOrder->setParameter("trade_type", "NATIVE");//Transaction type
        //Get unified payment interface result
        $unifiedOrderResult = $unifiedOrder->getResult();
// var_dump($unifiedOrder);
        //The merchant sets the corresponding processing flow according to the actual situation
        if ($unifiedOrderResult["return_code"] == "FAIL") {             //The merchant adds the processing flow by itself             //echo "Communication error:". $unifiedOrderResult['return_msg']. "<br>";             $data = array(                 'code' => 2,




                'msg' => "Communication error:". $unifiedOrderResult['return_msg']
            );
        } elseif ($unifiedOrderResult["result_code"] == "FAIL") {             //The merchant adds the processing flow by itself // echo "error code :". $unifiedOrderResult['err_code']. "<br>"; // echo "Description of error code:". $unifiedOrderResult['err_code_des']. "<br>";             $data = array(                 'code' = > 3,                 'msg' => "Error code:". $unifiedOrderResult['err_code']. "<br>Description of error code:". $unifiedOrderResult['err_code_des']             );         } elseif ($unifiedOrderResult["code_url"] != NULL) {             //Get the code_url from the unified payment interface             $code_url = $unifiedOrderResult["code_url"];










            if (substr($code_url, 0, 6) == "weixin") {
                ob_start();
                $QRcode = new \QRcode();
                $QRcode::png($code_url);
                $imageString = base64_encode(ob_get_contents());
                ob_end_clean();
                $data = array(
                    'code' => 1,
                    'msg' => 'success',
                    'url' => "data:image/png;base64," . $imageString,
                    'url2' => $code_url,
                    'order_id' => $order_num
                );
            } else {
                header('HTTP/1.1 404 Not Found');
            }

        } else {
            $data = array(
                'code' => 4,
                'msg' => 'error'
            );
        }
        $this->ajaxReturn($data);
    }

    /*
     *WeChat asynchronous callback address
     */
    public function wxNotify()
    {         vendor('WxPcpay.WxPayPubHelper');         //Use the general notification interface         $notify = new \Notify_pub();         //Store WeChat callback         $xml = $GLOBALS ['HTTP_RAW_POST_DATA'];         $notify->saveData($xml); // var_dump($xml);         //Verify the signature and respond to WeChat.         //When interacting with background notifications, if WeChat receives a response from the merchant that is not successful or timed out, WeChat considers the notification to have failed.         //WeChat will periodically re-initiate notifications through a certain strategy (for example, 8 times in 30 minutes),         //as much as possible Improve the success rate of notifications, but WeChat does not guarantee that notifications will eventually succeed.         if ($notify->checkSign() == FALSE) {             $notify->setReturnParameter("return_code", "FAIL");//Return status code













            $notify->setReturnParameter("return_msg", "Signature failed");//Return information
        } else {             $notify->setReturnParameter("return_code", "SUCCESS");//Set return code         }         $returnXml = $notify- >returnXml();         echo $returnXml;         //== The merchant sets the corresponding processing flow according to the actual situation, here is just an example =======         //Record the callback information in the form of a log file         // $log_ = new Log_(); // $log_name= __ROOT__."/Public/notify_url.log";//log file path // $this->log_result($log_name,"[received notify notification]:\n".$ xml."\n");         if ($notify->checkSign() == TRUE) {             if ($notify->data["return_code"] == "FAIL" ) {                 //Order status should be updated here, merchants add and delete operations by themselves












                //log_result($log_name,"[Communication error]:\n".$xml."\n");
                $this->error("Communication error");
            } elseif ($notify->data["result_code" ] == "FAIL") {                 //The order status should be updated here, and the merchant should add and delete operations on its own // log_result($log_name,"[Business Error]:\n".$xml."\n");                 $this ->error("Business error");             } elseif ($notify->data['return_code'] == "SUCCESS" && $notify->data['result_code'] == "SUCCESS") {                 //Database Operation                 $out_trade_no = $notify->data['out_trade_no'];                 $transaction_id = $notify->data['transaction_id'];                 $ini['order_num'] = $out_trade_no;                 $res = M('account_order')->where($ini)->find();









                if($res['status'] == 1){
                     $this->orderResult($out_trade_no,$transaction_id);
                }
                return true;
                //$this->success("支付成功!");
            } else {
                $this->error("UNKNOW ERROR");
            }
        }
    }
    /*
     * 是否充值
     */
    public function orderQuery()
    {
        $out_trade_no = I('post.out_trade_no');
        $ini['order_num'] = $out_trade_no;
        $res = M('account_order')->where($ini)->field('order_id,status')->find();
        if ($res['order_id']) {
            if ($res['status'] == 2) {
                $arr = array(
                    'code' => 1,
                    'msg' => 'success'
                );
            } else {
                $arr = array(
                    'code' => 3,
                    'msg' => 'error2'
                );
            }
        } else {
            $arr = array(
                'code' => 2,
                'msg' => 'error1'
            );
        }
        $this->ajaxReturn($arr);
    }

The html of the page generated by the QR code

<div class="layui-form-item">
   <div class="layui-inline">
        <button class="layui-btn" type="button" id="recharge">去充值</button>
    </div>
 </div>
<script>
    $(function () {
      $("#recharge").click(function () {
        var invoice_type = $("input[name='invoice_type']:checked").val();//是否开票
        var pay_type = $("input[name='pay_type']:checked").val();//支付方式
        var amount = $("#amount").val();
        if(pay_type == 1){
            $.post("{:U('Pay/wxPay')}",{
                invoice_type:invoice_type,
                pay_type:pay_type,
                amount:amount
            },function (data) {
                console.log(data);
                if(data.code == 1){
                    $("#order_id").val(data.order_id);
                    layer.open({
                        type: 1,
                        title: false,
                        closeBtn: 0,
                        shadeClose: true,
                        skin: 'yourclass',
                        content: '<img alt="模式二扫码支付" src="'+data.url+'" style="width:200px;height:200px;"/>'
                    });
                }

            },'json')
        }else{
           location.href="/suptem/Pay/alipayOrder?invoice_type="+invoice_type+'&amount='+amount;
        }

    });
</script> 
<script language="JavaScript">
    function Check(){
        var out_trade_no = $('#order_id').val();
        if(out_trade_no){
            $.post("{:U('Pay/orderQuery')}", { out_trade_no: out_trade_no},
                function(data){
                    if(data.msg == "success"){
                        window.location = "{:U('balanceRecord')}";
                    }
                },'json');
        }
    }
    window.setInterval("Check()",3000);
</script>

After the WeChat client payment is successful, the page will automatically jump to the successful payment page

Guess you like

Origin blog.csdn.net/weixin_38615720/article/details/101362686