[Record] Use of PHP WeChat applet WeChat payment v3

藏色散人
Release: 2021-07-15 13:47:09
forward
4145 people have browsed it

Writing a small program and found that WeChat payment has v3 version, I thought about taking a new payment, but found that it was poisonous, record the process

First place the order in a unified manner

//统一下单
public function wechartAddOrder($name,$ordernumber,$money,$openid){
        $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
        $urlarr = parse_url($url);
        $appid = config('config.appId');//appID
        $mchid = config('config.mchid');//商户ID
        $xlid = config('config.apiXL');//API序列号
        $data = array();
        $randstr = getRanStr(16,false);//随机字符串长度不超过32
        $time = time();
        $data['appid'] = $appid;
        $data['mchid'] = $mchid;
        $data['description'] = $name;//商品描述
        $data['out_trade_no'] = $ordernumber;//订单编号
        $data['notify_url'] = "https://www.xffly.cn/api/admin/order/wechartCallback";//回调接口
//      $data['amount']['total'] = $money;//金额
        $data['amount']['total'] = 1;
        $data['payer']['openid'] = $openid;//用户openID
        $data = json_encode($data); 
        $key = $this->getSign($data,$urlarr['path'],$randstr,$time);//签名
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"',$mchid,$xlid,$randstr,$time,$key);//头部信息
        $header  = array(
            'Content-Type:'.'application/json; charset=UTF-8',
            'Accept:application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 '.$token
        );  
        $ret = curl_post_https($url,$data,$header);
        return $ret;
    }
Copy after login

To calculate the signature, I have done it many times according to the document

//微信支付签名
public function getSign($data=array(),$url,$randstr,$time){
        $str = "POST"."\n".$url."\n".$time."\n".$randstr."\n".$data."\n";
        $key = file_get_contents('apiclient_key.pem');//在商户平台下载的秘钥
        $str = getSha256WithRSA($str,$key);
        return $str;
    }
Copy after login

Get the prepay_id through the unified ordering interface
Use its wx.requestPayment interface to activate the payment in the mini program. It has no content, so I won’t post the code. , write according to the document
In which a signature is required to initiate payment, similarly

//调起支付的签名
public function getWechartSign($post){
        $data = array();
        $data['timeStamp'] = $post['timeStamp'];
        $data['nonceStr'] = $post['str'];
        $data['package'] = $post['package'];
        $str = config('config.appId')."\n".$data['timeStamp']."\n".$data['nonceStr']."\n".$data['package']."\n";
        $key = file_get_contents('apiclient_key.pem');
        $str = getSha256WithRSA($str,$key);
        return $str;
    }
Copy after login

The focus is the callback of successful payment, which is simply poisonous
The json information returned, json_decode parsing becomes empty , it can be parsed after copying it, maybe it has BOM information, but it is not easy to use. Use htmlspecialchars_decode to escape it. The debugging tool can be successful, but the real WeChat payment still doesn't work. In the end, there is no way to save it. In the log, you can fetch it yourself and you can use it.

//微信回调写入日志文件并返回
    public function writeWechartLog($post){
        if(!is_dir("upload/log")){
           mkdir("upload/log",0777,true);
        }
        $log = fopen("upload/log/wechart.txt", "a+");
        if(is_array($post)){
            $post = json_encode($post);
        }
        fwrite($log, $post."\n");
        fclose($log);
        $read = fopen("upload/log/wechart.txt", "r");
        fseek($read, -1, SEEK_END);
        $s = '';
        while (($c = fgetc($read)) !== false) {
            if ($c == "\n" && $s) break;
            $s = $c . $s;
            fseek($read, -2, SEEK_CUR);
        }
        fclose($read);
        return $s;//取刚刚存的最后一条回调信息
    }
Copy after login

In the callback information, there is something encrypted and you need to decrypt it. The data passed in is the data you fetched from the log
sodium_crypto_aead_aes256gcm_decrypt This decryption method requires the PHP extension sodium

//微信回调解密
    public function wechartDecrypt($str) {
        $str = htmlspecialchars_decode($str,ENT_COMPAT);
        $post = json_decode($str,true);
        $key = config("config.apiv3Key");//商户平台设置的api v3 密码
        $text = base64_decode($post['resource']['ciphertext']);
        $str = sodium_crypto_aead_aes256gcm_decrypt($text,$post['resource']['associated_data'],$post['resource']['nonce'],$key);
        return json_decode($str,true);
    }
Copy after login

Then the business processing after getting the callback information

Friends who read this article again, if you know why the json returned by the WeChat callback The information cannot be used directly, please tell me, thank you, I haven’t figured it out after a day of research, so I can only deal with it like this first...

The above is the detailed content of [Record] Use of PHP WeChat applet WeChat payment v3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jianshu.com
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