search
HomeWeChat AppletWeChat Development[Record] Use of PHP WeChat applet WeChat payment v3

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;
    }

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;
    }

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;
    }

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;//取刚刚存的最后一条回调信息
    }

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);
    }

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!

Statement
This article is reproduced at:jianshu. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor