[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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
