


Example analysis of implementing APP WeChat payment through PHP
Mar 05, 2018 pm 01:47 PM Nowadays, using APP WeChat payment has become the mainstream payment mode. Below, the editor will introduce to you an example explanation of how to implement APP WeChat payment through PHP. , it is simple and easy to learn. Let’s learn APP with the editor Pay with WeChat.
1. The PHP background generates a prepayment transaction order, returns the correct prepayment transaction response ID, and then calls up the payment in the APP!
Official document:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1
Spliced ??according to the document The parameters required by WeChat need several methods. Just upload the code!
The parameters transmitted to WeChat must be assembled into xml format and sent as parameter array!
public function ToXml($data=array()) { if(!is_array($data) || count($data) <= 0) { return '數(shù)組異常'; } $xml = "<xml>"; foreach ($data as $key=>$val) { if (is_numeric($val)){ $xml.="<".$key.">".$val."</".$key.">"; }else{ $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; } } $xml.="</xml>"; return $xml; }
2. Generate random characters String, the parameters required by WeChat! There are many methods here, it depends on your hobbies!
function rand_code(){ $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62個(gè)字符 $str = str_shuffle($str); $str = substr($str,0,32); return $str; }
3. This is an important step for WeChat, this method will be used many times! Generate signature
private function getSign($params) { ksort($params); //將參數(shù)數(shù)組按照參數(shù)名ASCII碼從小到大排序 foreach ($params as $key => $item) { if (!empty($item)) { //剔除參數(shù)值為空的參數(shù) $newArr[] = $key.'='.$item; // 整合新的參數(shù)數(shù)組 } } $stringA = implode("&", $newArr); //使用 & 符號連接參數(shù) $stringSignTemp = $stringA."&key="."************************"; //拼接key // key是在商戶平臺API安全里自己設(shè)置的 $stringSignTemp = MD5($stringSignTemp); //將字符串進(jìn)行MD5加密 $sign = strtoupper($stringSignTemp); //將所有字符轉(zhuǎn)換為大寫 return $sign; }
4. Pass the parameters to WeChat and generate a pre-payment order! Receive the data returned by WeChat and send it back to the APP. The APP calls the payment interface to complete the payment! For the parameters required on the APP, please see the WeChat documentation: https://pay. weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12&index=2
public function wx_pay() { $nonce_str = $this->rand_code(); //調(diào)用隨機(jī)字符串生成方法獲取隨機(jī)字符串 $data['appid'] ='wxdbc5dc*******'; //appid $data['mch_id'] = '1493*****' ; //商戶號 $data['body'] = "APP支付測試"; $data['spbill_create_ip'] = $_SERVER['HTTP_HOST']; //ip地址 $data['total_fee'] = 1; //金額 $data['out_trade_no'] = time().mt_rand(10000,99999); //商戶訂單號,不能重復(fù) $data['nonce_str'] = $nonce_str; //隨機(jī)字符串 $data['notify_url'] = 'http://xxx.xxx.com/wx_notify'; //回調(diào)地址,用戶接收支付后的通知,必須為能直接訪問的網(wǎng)址,不能跟參數(shù) $data['trade_type'] = 'APP'; //支付方式 //將參與簽名的數(shù)據(jù)保存到數(shù)組 注意:以上幾個(gè)參數(shù)是追加到$data中的,$data中應(yīng)該同時(shí)包含開發(fā)文檔中要求必填的剔除sign以外的所有數(shù)據(jù) $data['sign'] = $this->getSign($data); //獲取簽名 $xml = $this->ToXml($data); //數(shù)組轉(zhuǎn)xml //curl 傳遞給微信方 $url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //header("Content-type:text/xml"); $ch = curl_init(); curl_setopt($ch,CURLOPT_URL, $url); if(stripos($url,"https://")!==FALSE){ curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); } else { curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//嚴(yán)格校驗(yàn) } //設(shè)置header curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1); curl_setopt($ch, CURLOPT_HEADER, FALSE); //要求結(jié)果為字符串且輸出到屏幕上 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //設(shè)置超時(shí) curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_POST, TRUE); //傳輸文件 curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); //運(yùn)行curl $data = curl_exec($ch); //返回結(jié)果 if($data){ curl_close($ch); //返回成功,將xml數(shù)據(jù)轉(zhuǎn)換為數(shù)組. $re = $this->FromXml($data); if($re['return_code'] != 'SUCCESS'){ json("201",'簽名失敗'); } else{ //接收微信返回的數(shù)據(jù),傳給APP! $arr =array( 'prepayid' =>$re['prepay_id'], 'appid' => 'wxdbc5dc*****', 'partnerid' => '14937****', 'package' => 'Sign=WXPay', 'noncestr' => $nonce_str, 'timestamp' =>time(), ); //第二次生成簽名 $sign = $this->getSign($arr); $arr['sign'] = $sign; json('200','簽名成功',$arr); } } else { $error = curl_errno($ch); curl_close($ch); json('201',"curl出錯(cuò),錯(cuò)誤碼:$error"); } }
5. Convert xml data into an array, used when receiving data returned by WeChat.
public function FromXml($xml) { if(!$xml){ echo "xml數(shù)據(jù)異常!"; } //將XML轉(zhuǎn)為array //禁止引用外部xml實(shí)體 libxml_disable_entity_loader(true); $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $data; }
2. After the APP payment is successful, it will call the callback address you filled in.
For details of the return parameters, please refer to the WeChat documentation: https://pay. weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_7&index=3
// 微信支付回調(diào) function wx_notify(){ //接收微信返回的數(shù)據(jù)數(shù)據(jù),返回的xml格式 $xmlData = file_get_contents('php://input'); //將xml格式轉(zhuǎn)換為數(shù)組 $data = $this->FromXml($xmlData); //用日志記錄檢查數(shù)據(jù)是否接受成功,驗(yàn)證成功一次之后,可刪除。 $file = fopen('./log.txt', 'a+'); fwrite($file,var_export($data,true)); //為了防止假數(shù)據(jù),驗(yàn)證簽名是否和返回的一樣。 //記錄一下,返回回來的簽名,生成簽名的時(shí)候,必須剔除sign字段。 $sign = $data['sign']; unset($data['sign']); if($sign == $this->getSign($data)){ //簽名驗(yàn)證成功后,判斷返回微信返回的 if ($data['result_code'] == 'SUCCESS') { //根據(jù)返回的訂單號做業(yè)務(wù)邏輯 $arr = array( 'pay_status' => 1, ); $re = M('order')->where(['order_sn'=>$data['out_trade_no']])->save($arr); //處理完成之后,告訴微信成功結(jié)果! if($re){ echo '<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml>';exit(); } } //支付失敗,輸出錯(cuò)誤信息 else{ $file = fopen('./log.txt', 'a+'); fwrite($file,"錯(cuò)誤信息:".$data['return_msg'].date("Y-m-d H:i:s"),time()."\r\n"); } } else{ $file = fopen('./log.txt', 'a+'); fwrite($file,"錯(cuò)誤信息:簽名驗(yàn)證失敗".date("Y-m-d H:i:s"),time()."\r\n"); } }
Here, the WeChat APP payment process is completed successfully! Thank you for your support!
The above is the specific method of implementing APP WeChat payment in PHP. Through the editor's example explanation, I believe everyone has mastered it.
Related recommendations:
Alarm notification example of WeChat payment
WeChat refund function example of PHP WeChat payment development
Thinkphp integrated WeChat payment function detailed explanation
The above is the detailed content of Example analysis of implementing APP WeChat payment through PHP. 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

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

LateStaticBindinginPHPallowsstatic::torefertotheclassinitiallycalledatruntimeininheritancescenarios.BeforePHP5.3,self::alwaysreferencedtheclasswherethemethodwasdefined,causingChildClass::sayHello()tooutput"ParentClass".Withlatestaticbinding
