[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

Undress AI Tool
Undress images for free

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

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

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)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

TestthePDFinanotherapptodetermineiftheissueiswiththefileorEdge.2.Enablethebuilt-inPDFviewerbyturningoff"AlwaysopenPDFfilesexternally"and"DownloadPDFfiles"inEdgesettings.3.Clearbrowsingdataincludingcookiesandcachedfilestoresolveren

UseGuzzleforrobustHTTPrequestswithheadersandtimeouts.2.ParseHTMLefficientlywithSymfonyDomCrawlerusingCSSselectors.3.HandleJavaScript-heavysitesbyintegratingPuppeteerviaPHPexec()torenderpages.4.Respectrobots.txt,adddelays,rotateuseragents,anduseproxie

To become a master of Yii, you need to master the following skills: 1) Understand Yii's MVC architecture, 2) Proficient in using ActiveRecordORM, 3) Effectively utilize Gii code generation tools, 4) Master Yii's verification rules, 5) Optimize database query performance, 6) Continuously pay attention to Yii ecosystem and community resources. Through the learning and practice of these skills, the development capabilities under the Yii framework can be comprehensively improved.

In VSCode, you can quickly switch the panel and editing area through shortcut keys. To jump to the left Explorer panel, use Ctrl Shift E (Windows/Linux) or Cmd Shift E (Mac); return to the editing area to use Ctrl ` or Esc or Ctrl 1~9. Compared to mouse operation, keyboard shortcuts are more efficient and do not interrupt the encoding rhythm. Other tips include: Ctrl KCtrl E Focus Search Box, F2 Rename File, Delete File, Enter Open File, Arrow Key Expand/Collapse Folder.

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

RuntheWindowsUpdateTroubleshooterviaSettings>Update&Security>Troubleshoottoautomaticallyfixcommonissues.2.ResetWindowsUpdatecomponentsbystoppingrelatedservices,renamingtheSoftwareDistributionandCatroot2folders,thenrestartingtheservicestocle
