亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home WeChat Applet WeChat Development Example analysis of implementing APP WeChat payment through PHP

Example analysis of implementing APP WeChat payment through PHP

Mar 05, 2018 pm 01:47 PM
php Case Analysis pay

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 &#39;數(shù)組異常&#39;;
 }
 $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 = &#39;0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;;//62個字符
 $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.&#39;=&#39;.$item; // 整合新的參數(shù)數(shù)組
  }
 }
 $stringA = implode("&", $newArr);  //使用 & 符號連接參數(shù)
 $stringSignTemp = $stringA."&key="."************************"; //拼接key
 // key是在商戶平臺API安全里自己設(shè)置的
 $stringSignTemp = MD5($stringSignTemp); //將字符串進行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)用隨機字符串生成方法獲取隨機字符串
 $data[&#39;appid&#39;] =&#39;wxdbc5dc*******&#39;; //appid
 $data[&#39;mch_id&#39;] = &#39;1493*****&#39; ; //商戶號
 $data[&#39;body&#39;] = "APP支付測試";
 $data[&#39;spbill_create_ip&#39;] = $_SERVER[&#39;HTTP_HOST&#39;]; //ip地址
 $data[&#39;total_fee&#39;] = 1;    //金額
 $data[&#39;out_trade_no&#39;] = time().mt_rand(10000,99999); //商戶訂單號,不能重復
 $data[&#39;nonce_str&#39;] = $nonce_str;   //隨機字符串
 $data[&#39;notify_url&#39;] = &#39;http://xxx.xxx.com/wx_notify&#39;; //回調(diào)地址,用戶接收支付后的通知,必須為能直接訪問的網(wǎng)址,不能跟參數(shù)
 $data[&#39;trade_type&#39;] = &#39;APP&#39;; //支付方式
 //將參與簽名的數(shù)據(jù)保存到數(shù)組 注意:以上幾個參數(shù)是追加到$data中的,$data中應(yīng)該同時包含開發(fā)文檔中要求必填的剔除sign以外的所有數(shù)據(jù)
 $data[&#39;sign&#39;] = $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);//嚴格校驗
 }
 //設(shè)置header
 curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
 curl_setopt($ch, CURLOPT_HEADER, FALSE);
 //要求結(jié)果為字符串且輸出到屏幕上
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
 //設(shè)置超時
 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
 curl_setopt($ch, CURLOPT_POST, TRUE);
 //傳輸文件
 curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
 //運行curl
 $data = curl_exec($ch);
 //返回結(jié)果
 if($data){
  curl_close($ch);
  //返回成功,將xml數(shù)據(jù)轉(zhuǎn)換為數(shù)組.
  $re = $this->FromXml($data);
  if($re[&#39;return_code&#39;] != &#39;SUCCESS&#39;){
  json("201",&#39;簽名失敗&#39;);
  }
  else{
  //接收微信返回的數(shù)據(jù),傳給APP!
  $arr =array(
   &#39;prepayid&#39; =>$re[&#39;prepay_id&#39;],
   &#39;appid&#39; => &#39;wxdbc5dc*****&#39;,
   &#39;partnerid&#39; => &#39;14937****&#39;,
   &#39;package&#39; => &#39;Sign=WXPay&#39;,
   &#39;noncestr&#39; => $nonce_str,
   &#39;timestamp&#39; =>time(),
  );
  //第二次生成簽名
  $sign = $this->getSign($arr);
  $arr[&#39;sign&#39;] = $sign;
  json(&#39;200&#39;,&#39;簽名成功&#39;,$arr);
  }
 } else {
  $error = curl_errno($ch);
  curl_close($ch);
  json(&#39;201&#39;,"curl出錯,錯誤碼:$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實體
 libxml_disable_entity_loader(true);
 $data = json_decode(json_encode(simplexml_load_string($xml, &#39;SimpleXMLElement&#39;, 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(&#39;php://input&#39;);
  //將xml格式轉(zhuǎn)換為數(shù)組
  $data = $this->FromXml($xmlData);
  //用日志記錄檢查數(shù)據(jù)是否接受成功,驗證成功一次之后,可刪除。
  $file = fopen(&#39;./log.txt&#39;, &#39;a+&#39;);
  fwrite($file,var_export($data,true));
  //為了防止假數(shù)據(jù),驗證簽名是否和返回的一樣。
  //記錄一下,返回回來的簽名,生成簽名的時候,必須剔除sign字段。
  $sign = $data[&#39;sign&#39;];
  unset($data[&#39;sign&#39;]);
  if($sign == $this->getSign($data)){
  //簽名驗證成功后,判斷返回微信返回的
  if ($data[&#39;result_code&#39;] == &#39;SUCCESS&#39;) {
  //根據(jù)返回的訂單號做業(yè)務(wù)邏輯
  $arr = array(
   &#39;pay_status&#39; => 1,
   );
  $re = M(&#39;order&#39;)->where([&#39;order_sn&#39;=>$data[&#39;out_trade_no&#39;]])->save($arr);
  //處理完成之后,告訴微信成功結(jié)果!
  if($re){
   echo &#39;<xml>
  <return_code><![CDATA[SUCCESS]]></return_code>
  <return_msg><![CDATA[OK]]></return_msg>
  </xml>&#39;;exit();
  }
  }
  //支付失敗,輸出錯誤信息
  else{
  $file = fopen(&#39;./log.txt&#39;, &#39;a+&#39;);
  fwrite($file,"錯誤信息:".$data[&#39;return_msg&#39;].date("Y-m-d H:i:s"),time()."\r\n"); 
  }
 }
 else{
  $file = fopen(&#39;./log.txt&#39;, &#39;a+&#39;);
  fwrite($file,"錯誤信息:簽名驗證失敗".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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution Jul 25, 2025 pm 07:06 PM

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.

See all articles