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

Home WeChat Applet WeChat Development Detailed explanation of Thinkphp integrating WeChat payment function

Detailed explanation of Thinkphp integrating WeChat payment function

Dec 02, 2017 am 10:21 AM
php thinkphp Detailed explanation

WeChat payment is now common in our lives, and WeChat applets are also very popular during development. In this article, we will continue to explain to you about Thinkphp’s integration of WeChat payment functions.

1. WeChat public account:

Set the domain name that can obtain user ID information permissions among the unique appid, appscrect, and interface permissions (each user will have a unique ID for different publics. Obtain the basic information of the user's WeChat account through this ID (see the WeChat developer documentation for details), set the WeChat payment authorization directory on the WeChat payment button (written to the level of the controller that initiates the request), and set the developer's WeChat account as a test whitelist (Required when using WeChat developer tools)

2. WeChat payment platform:

Merchant platform login account, payment key (you can set it yourself at any time, there can only be one),

3. Integrate the logic into thinkphp:

Set the front-end WeChat payment button and click to call the payment initiation controller method,

The controller runs, references the WeChat payment class, and obtains the user openid , obtain the order data, splice out all the data required by ordinary merchants' prepayment jsp, display the customized payment page,

Click to pay on the payment page, and call the jspi script function provided by WeChat to initiate payment to initiate payment. ,

After the payment is completed, the page will redirect to (the jump directory {:U('controller/function)} set in the script function of the custom payment page), and the asynchronous (silent) setting will be Processing order logic (recording payment time, marking as paid, marking as WeChat payment), etc.

Code:

WeChat payment button on my order page:

WeChat Payment

Initiate payment controller Wxpay:

<?php
namespace Home\Controller;
use Think\Controller;
//微信支付類
class WxpayController extends Controller {
 //獲取access_token過程中的跳轉(zhuǎn)uri,通過跳轉(zhuǎn)將code傳入jsapi支付頁面
 public function js_api_start(){
  if(!empty($_GET[&#39;order_key_num&#39;])){
   // session(array(&#39;pay_now_id&#39;=>$_GET[&#39;order_key_num&#39;],&#39;expire&#39;=>3600));
   S(&#39;pay_now_id&#39;,$_GET[&#39;order_key_num&#39;],3600);
  }
  vendor(&#39;Weixinpay.WxPayPubHelper&#39;);
  //使用jsapi接口
  $jsApi = new \JsApi_pub();
  //=========步驟1:網(wǎng)頁授權(quán)獲取用戶openid============
  //通過code獲得openid
   if($_GET[&#39;code&#39;] == &#39;&#39;){
   //跳轉(zhuǎn)
    $redirect_uri = &#39;https://當(dāng)前域名+模塊+控制器+方法&#39;;
    $url = &#39;https://open.weixin.qq.com/connect/oauth2/authorize
    ?appid=公眾號(hào)特有IDredirect_uri=&#39;.$redirect_uri.&#39;&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect&#39;;
    header("Location: $url");
    exit();
   }else{
   //獲取openid
   $url = &#39;https://api.weixin.qq.com/sns/oauth2/access_token
   ?appid=公眾號(hào)ID&secret=公眾號(hào)scrept&code=&#39;.$_GET[&#39;code&#39;].&#39;&grant_type=authorization_code&#39;; 
   $openid_arr = json_decode(file_get_contents($url),true);
  }
  $openid=$openid_arr[&#39;openid&#39;];
  $pay_now_id = S(&#39;pay_now_id&#39;);
  if($pay_now_id){
   $id=$pay_now_id;
   $o = D(&#39;order_info&#39;);
   $order_info = $o->where(&#39;order_id = %d&#39;,$id)->find();
   if(empty($order_info[&#39;paycode&#39;])){
    $order_info[&#39;paycode&#39;] = &#39;weixin&#39;;
   }
   if($order_info[&#39;is_pay&#39;]){
    $this->error(&#39;當(dāng)前訂單已經(jīng)支付&#39;);
   }
  }else{
   $this->error("不存在當(dāng)前訂單編號(hào)!");
  }
   $res = array(
   &#39;order_sn&#39; => $order_info[&#39;order_sn&#39;],
   &#39;order_amount&#39; => $order_info[&#39;pay_money&#39;]
   );
  //=========步驟2:使用統(tǒng)一支付接口,獲取prepay_id============
  //使用統(tǒng)一支付接口
  $unifiedOrder = new \UnifiedOrder_pub();
  //設(shè)置統(tǒng)一支付接口參數(shù)
  //設(shè)置必填參數(shù)
  //appid已填,商戶無需重復(fù)填寫
  //mch_id已填,商戶無需重復(fù)填寫
  //noncestr已填,商戶無需重復(fù)填寫
  //spbill_create_ip已填,商戶無需重復(fù)填寫
  //sign已填,商戶無需重復(fù)填寫
  $total_fee = $order_info[&#39;pay_money&#39;]*100;
  // $total_fee = $res[&#39;order_amount&#39;];
  //$total_fee = 1;
  // var_dump($order_info[&#39;pay_money&#39;]);die;
  $body = "訂單支付";
  $unifiedOrder->setParameter("openid", "$openid");//用戶標(biāo)識(shí)
  $unifiedOrder->setParameter("body", &#39;商品采購&#39;);//商品描述
  //自定義訂單號(hào),此處僅作舉例
  $unifiedOrder->setParameter("out_trade_no", $order_info[&#39;order_sn&#39;]);//商戶訂單號(hào) 
  $unifiedOrder->setParameter("total_fee", $total_fee);//總金額
  //$unifiedOrder->setParameter("attach", "order_sn={$res[&#39;order_sn&#39;]}");//附加數(shù)據(jù) 
  $unifiedOrder->setParameter("notify_url", \WxPayConf_pub::NOTIFY_URL);//通知地址 
  $unifiedOrder->setParameter("trade_type", "JSAPI");//交易類型
  //非必填參數(shù),商戶可根據(jù)實(shí)際情況選填
  //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商戶號(hào) 
  //$unifiedOrder->setParameter("device_info","XXXX");//設(shè)備號(hào) 
  //$unifiedOrder->setParameter("attach","XXXX");//附加數(shù)據(jù) 
  //$unifiedOrder->setParameter("time_start","XXXX");//交易起始時(shí)間
  //$unifiedOrder->setParameter("time_expire","XXXX");//交易結(jié)束時(shí)間 
  //$unifiedOrder->setParameter("goods_tag","XXXX");//商品標(biāo)記 
  //$unifiedOrder->setParameter("openid","XXXX");//用戶標(biāo)識(shí)
  //$unifiedOrder->setParameter("product_id","XXXX");//商品ID
  $prepay_id = $unifiedOrder->getPrepayId();
  // var_dump($prepay_id);die;
  //=========步驟3:使用jsapi調(diào)起支付============
  $jsApi->setPrepayId($prepay_id);
  $jsApiParameters = $jsApi->getParameters();
  $wxconf = json_decode($jsApiParameters, true);
  if ($wxconf[&#39;package&#39;] == &#39;prepay_id=&#39;) {
   $this->error(&#39;當(dāng)前訂單存在異常!&#39;);
  }
  $this->assign(&#39;res&#39;, $res);
  $this->assign(&#39;jsApiParameters&#39;, $jsApiParameters);
  $this->display(&#39;jsapi&#39;);
 }
 //異步通知url,商戶根據(jù)實(shí)際開發(fā)過程設(shè)定
 public function notify_url() {
  vendor(&#39;Weixinpay.WxPayPubHelper&#39;);
  //使用通用通知接口
  $notify = new \Notify_pub();
  //存儲(chǔ)微信的回調(diào)
  $xml = $GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;]; 
  $notify->saveData($xml);
  //驗(yàn)證簽名,并回應(yīng)微信。
  //對(duì)后臺(tái)通知交互時(shí),如果微信收到商戶的應(yīng)答不是成功或超時(shí),微信認(rèn)為通知失敗,
  //微信會(huì)通過一定的策略(如30分鐘共8次)定期重新發(fā)起通知,
  //盡可能提高通知的成功率,但微信不保證通知最終能成功。
  if($notify->checkSign() == FALSE){
   $notify->setReturnParameter("return_code", "FAIL");//返回狀態(tài)碼
   $notify->setReturnParameter("return_msg", "簽名失敗");//返回信息
  }else{
   $notify->setReturnParameter("return_code", "SUCCESS");//設(shè)置返回碼
  }
  $returnXml = $notify->returnXml();
  //==商戶根據(jù)實(shí)際情況設(shè)置相應(yīng)的處理流程,此處僅作舉例=======
  //以log文件形式記錄回調(diào)信息
  //$log_name = "notify_url.log";//log文件路徑
  //$this->log_result($log_name, "【接收到的notify通知】:\n".$xml."\n");
  $parameter = $notify->xmlToArray($xml);
  //$this->log_result($log_name, "【接收到的notify通知】:\n".$parameter."\n");
  if($notify->checkSign() == TRUE){
   if ($notify->data["return_code"] == "FAIL") {
    //此處應(yīng)該更新一下訂單狀態(tài),商戶自行增刪操作
    //$this->log_result($log_name, "【通信出錯(cuò)】:\n".$xml."\n");
    //更新訂單數(shù)據(jù)【通信出錯(cuò)】設(shè)為無效訂單
    echo &#39;error&#39;;
   }
   else if($notify->data["result_code"] == "FAIL"){
    //此處應(yīng)該更新一下訂單狀態(tài),商戶自行增刪操作
    //$this->log_result($log_name, "【業(yè)務(wù)出錯(cuò)】:\n".$xml."\n");
    //更新訂單數(shù)據(jù)【通信出錯(cuò)】設(shè)為無效訂單
    echo &#39;error&#39;;
   }
   else{
    //$this->log_result($log_name, "【支付成功】:\n".$xml."\n");
    //我這里用到一個(gè)process方法,成功返回?cái)?shù)據(jù)后處理,返回地?cái)?shù)據(jù)具體可以參考微信的文檔
    if ($this->process($parameter)) {
     //處理成功后輸出success,微信就不會(huì)再下發(fā)請(qǐng)求了
     echo &#39;success&#39;;
    }else {
     //沒有處理成功,微信會(huì)間隔的發(fā)送請(qǐng)求
     echo &#39;error&#39;;
    }
   }
  }
 }
 //訂單處理
 private function process($parameter) {
  //此處應(yīng)該更新一下訂單狀態(tài),商戶自行增刪操作
  /*
  * 返回的數(shù)據(jù)最少有以下幾個(gè)
  * $parameter = array(
   &#39;out_trade_no&#39; => xxx,//商戶訂單號(hào)
   &#39;total_fee&#39; => XXXX,//支付金額
   &#39;openid&#39; => XXxxx,//付款的用戶ID
  );
  */
  $data = array(
      &#39;order_sn&#39;=>$parameter[&#39;out_trade_no&#39;],
      &#39;des&#39;=>(&#39;訂單交易:&#39;.$parameter[&#39;out_trade_no&#39;]),
      &#39;money&#39;=>$parameter[&#39;total_fee&#39;],
     );
  orderhandlestarysdgdss($data);//這是一個(gè)common方法,他會(huì)將該訂單狀態(tài)設(shè)置為已支付之類的
  return true;
 }
}
?>

After initiating payment, splice the prepayment data parameters (see the WeChat ordinary merchant developer documentation for the parameter list - WeChat Payment - Unified Order) display page:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
<meta name="format-detection" content="telephone=no"/> 
<title>下</title>
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
<meta name="keyword" content="">
<meta name="description" content="">
<script type="text/javascript">
var order_sn = "{$res[&#39;order_sn&#39;]}";
//調(diào)用微信JS api 支付
function jsApiCall(){
 WeixinJSBridge.invoke(
  &#39;getBrandWCPayRequest&#39;,
  <?php echo $jsApiParameters; ?>,
  function(res){
   //如果支付成功
   if (res.err_msg == &#39;get_brand_wcpay_request:ok&#39;) {
    //支付成功后跳轉(zhuǎn)的地址
    location.href = "{:U(&#39;Home/User/my_order&#39;)}";
   }else if (res.err_msg == &#39;get_brand_wcpay_request:cancel&#39;) {
    alert(&#39;請(qǐng)盡快完成支付哦!&#39;);
   }else if (res.err_msg == &#39;get_brand_wcpay_request:fail&#39;) {
    alert(&#39;支付失敗&#39;);
   }else {
    alert(&#39;意外錯(cuò)誤&#39;);
   }
   //WeixinJSBridge.log(res.err_msg);
   //alert(res.err_code+res.err_desc+res.err_msg);
   /*if (res.err_msg == &#39;get_brand_wcpay_request:ok&#39;) {
    alert(&#39;支付成功&#39;);
   }else {
    alert(&#39;取消支付&#39;);
   }*/
  }
 );
}
function callpay(){
 if (typeof WeixinJSBridge == "undefined"){
  if( document.addEventListener ){
   document.addEventListener(&#39;WeixinJSBridgeReady&#39;, jsApiCall, false);
  }else if (document.attachEvent){
   document.attachEvent(&#39;WeixinJSBridgeReady&#39;, jsApiCall); 
   document.attachEvent(&#39;onWeixinJSBridgeReady&#39;, jsApiCall);
  }
 }else{
  jsApiCall();
 }
}
</script>
<style>
*{font-family:&#39;微軟雅黑&#39;,&#39;Microsoft YaHei&#39;;}
body #head{position:relative;z-index:99999999999999;padding:0 10px;}
body .zh-head{padding:0 0 0 0;height:auto;}
.zh-head-conter{position:relative;height:40px;}
.zh-logo{position:absolute;left:50%;top:0;margin:0 0 0 -60px;float:none;width:auto;}
.zh-logo a{display:block;}
.zh-logo img{width:120px;height:40px;display:block;}
.heads_fix .zh-logo{}
#head{position:fixed!important;left:0;top:0;right:0;z-index:99999;background:#fff;border-bottom:1px solid #ddd;}
.zh-logo{height:40px;}
.flowpay{margin-top:25%;}
.flowpay dt{text-align:center;}
.flowpay strong.price{font-size:40px;}
.wxLogo{text-align:center;}
.wxLogo img{}
.flowpay dd{margin:0;padding:20px 0 10px 0;}
.flowpay dd input{margin:0 auto;padding:0;width:90%;height:45px;line-height:45px;border:0;border-radius:4px;background:#0CBC0A;color:#fff;font-size:17px;display:block;-webkit-appearance:none;-moz-appearance:none;appearance:none;outline:none;}
</style>
</head>
<body>
<!--頭部開始-->
<div class="flowpay">
 <dl>
  <dt>
   <p class="wxLogo"><img src="/static/imghw/default1.png"  data-src="__PUBLIC__/home/images/1479953699138120.png"  class="lazy"   alt=""></p>
   本次訂單需支付:¥<strong class="price">{$res[&#39;order_amount&#39;]}</strong> 元
  </dt>
  <dd>
   <input type="button" id="hhhhhh" onclick="callpay()" value="立即支付" />
  </dd>
 </dl>
</div>
<!--尾結(jié)束-->
</body>
</html>

Then there is the class file:

Detailed explanation of Thinkphp integrating WeChat payment function

The cacert is the certificate storage directory; the certificate is not necessarily required;

## Just look for the #vendor folder in My Files.

The above content is about Thinkphp integrating WeChat payment function, I hope it can help everyone.

Related recommendations:

How to implement WeChat applet payment and refund in php

Introduction example of WeChat applet development

Encapsulation of network requests by WeChat applet

Example of password input by WeChat applet

WeChat applet Robot automatic customer service function

The above is the detailed content of Detailed explanation of Thinkphp integrating WeChat payment function. 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.

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.

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.

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