Home Backend Development PHP Tutorial Thinkphp implements WeChat public account payment interface

Thinkphp implements WeChat public account payment interface

Jun 08, 2018 am 11:13 AM

This article mainly introduces the Thinkphp WeChat public account payment interface in detail. Interested friends can refer to it.

The example of this article shares the Thinkphp WeChat public account payment interface for your reference. , the specific content is as follows

Step 1 First configure the two pictures in the folder to the same path except for changing the domain name to keep everything else consistent.

Step 2 Place the Weixinpay folder in \ThinkPHP\Library\Vendor Place the Weixinpay folder in this Vendor folder

Step 3 Place the php file WxJsAPIController.class.php in \Home\Controller

Step 4 Place the folder WxJsAPI in \Home\View

Step 5 Successfully call the WeChat official account payment function

jsApiCall.html

<!DOCTYPE html>
 <html>
 <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name=&#39;viewport&#39; content=&#39;width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0&#39;/>
  <title>微信安全支付</title>
  <script type="text/javascript">
    //调用微信JS api 支付
    function jsApiCall()
    {
      WeixinJSBridge.invoke(
        &#39;getBrandWCPayRequest&#39;,
        <?php echo $jsApiParameters; ?>,
        function(res){
          WeixinJSBridge.log(res.err_msg);
          if(res.err_msg == "get_brand_wcpay_request:ok"){
          //alert(res.err_code+res.err_desc+res.err_msg);
            /*这里写如果支付成功的话执行什么操作*/
          }else{
            //返回跳转到订单详情页面
            alert(支付失败);
              
          }
        }
      );
    }
    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>
 </head>
 <body>
 <button style="width:210px; height:30px; background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="jsApiCall()" id="asd" >购买</button>

  </p>
 </body>
 </html>
Copy after login

WxJsAPIController.class.php

<?php

namespace Home\Controller;
use Think\Controller;

class WxJsAPIController extends Controller{
  public function _initialize()
  {
    //引入WxPayPubHelper
    vendor(&#39;Weixinpay.WxPayPubHelper&#39;);
  }  

  public function jsApiCall()
  {  

    //使用jsapi接口
    $jsApi = new \JsApi_pub();
    
    //=========步骤1:网页授权获取用户openid============
    //通过code获得openid
    //
    //

    if (!isset($_GET[&#39;code&#39;]))
    {
      //触发微信返回code码
      $rUrl=urlencode(C(&#39;WxConfig.JS_API_CALL_URL&#39;).&#39;/id/&#39;.$_GET[id]);  
      /*注意一下这个 id 是为了可以成功的传个 id值才这样写 如果你不需要的话也可以直接写成
  $rUrl=urlencode(C(&#39;WxConfig.JS_API_CALL_URL&#39;));

      $this->redirect(&#39;WxJsAPI/jsApiCall&#39;,array(&#39;id&#39; =>55),0, &#39;页面跳转中...&#39;);
      我是这样穿这个id过来的值得你们也可以自己改成其他的来传这个id 或是删除他不要
      */
       

      $url = $jsApi->createOauthUrlForCode($rUrl);
      // echo $url;exit();
      Header("Location: $url");
    }else
    {

      //获取code码,以获取openid
      $code = $_GET[&#39;code&#39;];
      $jsApi->setCode($code);
      $openid = $jsApi->getOpenId();//openid 这里是为了获取用户当前的openid 如果你有做微信登陆的话就可以无视他。
    }



    //=========步骤2:使用统一支付接口,获取prepay_id============
    //使用统一支付接口
    $unifiedOrder = new \UnifiedOrder_pub();

      /*此处做数据库的查询 这里操作数据库把产品信息显示出来*/

      /*此处做数据库的查询 这里操作数据库把产品信息显示出来*/


    //设置统一支付接口参数
    //设置必填参数
    //appid已填,商户无需重复填写
    //mch_id已填,商户无需重复填写
    //noncestr已填,商户无需重复填写
    //spbill_create_ip已填,商户无需重复填写
    //sign已填,商户无需重复填写
    //

    $NOTIFY_URL="你的域名/index.php/Home/WxJsAPI/notify";

    $unifiedOrder->setParameter("openid",$openid);//openid
    $unifiedOrder->setParameter("body",&#39;商品的名字&#39;);//商品描述
    $unifiedOrder->setParameter("out_trade_no",&#39;123456789&#39;);//商户订单号
    $unifiedOrder->setParameter("total_fee",1*100);//总金额 微信的钱1*100等于1
    $unifiedOrder->setParameter("notify_url",$NOTIFY_URL);//通知地址
  

    $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
    //非必填参数,商户可根据实际情况选填
    //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
    //$unifiedOrder->setParameter("device_info","XXXX");//设备号
    //$unifiedOrder->setParameter("attach","XXXX");//附加数据
    //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
    //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
    //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
    //$unifiedOrder->setParameter("openid","XXXX");//用户标识
    //$unifiedOrder->setParameter("product_id","XXXX");//商品ID
  

    $prepay_id = $unifiedOrder->getPrepayId();

    // echo $prepay_id;exit();
    //=========步骤3:使用jsapi调起支付============
    $jsApi->setPrepayId($prepay_id);
    
    $jsApiParameters = $jsApi->getParameters();

    $WEB_HOST=&#39;你的域名&#39;;//填写的话 如 http://nicaicai.imwork.net 最后面不用加 /
    $this->assign(&#39;HOSTS&#39;,$WEB_HOST);
    $this->assign(&#39;jsApiParameters&#39;,$jsApiParameters);
    $this->display();
    //echo $jsApiParameters;

  }


  public function notify()
  {
    //使用通用通知接口
    $notify = new \Notify_pub();

    //存储微信的回调
    $xml = $GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;];   

    $notify->saveData($xml);
    

    //验证签名,并回应微信。
    //对后台通知交互时,如果微信收到商户的应答不是成功或超时,微信认为通知失败,
    //微信会通过一定的策略(如30分钟共8次)定期重新发起通知,
    //尽可能提高通知的成功率,但微信不保证通知最终能成功。
    if($notify->checkSign() == FALSE){

      $notify->setReturnParameter("return_code","FAIL");//返回状态码
      $notify->setReturnParameter("return_msg","签名失败了啊");//返回信息
    }else{
      $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
    }
    $returnXml = $notify->returnXml();
    echo $returnXml;
    
    //==商户根据实际情况设置相应的处理流程,此处仅作举例=======
    
    //以log文件形式记录回调信息
     // $log_ = new Log_();
    $log_name= __ROOT__."/Public/notify_url.log";//log文件路径
    
    
    if($notify->checkSign() == TRUE)
    {
      if ($notify->data["return_code"] == "FAIL") {


        //此处应该更新一下订单状态,商户自行增删操作
        log_result($log_name,"【通信出错】:\n".$xml."\n");
      }
      elseif($notify->data["result_code"] == "FAIL"){
    

        //此处应该更新一下订单状态,商户自行增删操作
        log_result($log_name,"【业务出错】:\n".$xml."\n");
      }
      else{ 

  /*查看支付成功的返回值请去 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 */

  $xmlss=$notify->data["out_trade_no"];//订单号
  $total_fee=$notify->data[&#39;total_fee&#39;];//订单总金额,单位为分,详见支付金额
    

    /*更新订单状态这里写数据库的操作*/
   
  /*更新订单状态这里写数据库的操作*/


        //此处应该更新一下订单状态,商户自行增删操作
        log_result($log_name,"【支付成功】:\n".$xml."\n");
      }
    
      //商户自行增加处理流程,
      //例如:更新订单状态
      //例如:数据库操作
      //例如:推送支付完成信息
    }
  }

  // 打印log
  public function log_result($file,$word)
  {
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX) ;
    fwrite($fp,"执行日期:".strftime("%Y-%m-%d-%H:%M:%S",time())."\n".$word."\n\n");
    flock($fp, LOCK_UN);
    fclose($fp);
  }

}


?>
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

thinkphp5 method of uploading pictures and generating thumbnails

thinkPHP3.2 implements WeChat access and Method of querying the token value

zen_cart method of generating an order before payment

The above is the detailed content of Thinkphp implements WeChat public account payment interface. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles