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
//統(tǒng)一下單 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";//回調(diào)接口 //??????$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
//調(diào)起支付的簽名 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.
//微信回調(diào)寫入日志文件并返回 ????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;//取剛剛存的最后一條回調(diào)信息 ????}
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
//微信回調(diào)解密 ????public?function?wechartDecrypt($str)?{ ????????$str?=?htmlspecialchars_decode($str,ENT_COMPAT); ????????$post?=?json_decode($str,true); ????????$key?=?config("config.apiv3Key");//商戶平臺設(shè)置的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)

Hot Topics

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
