Home php教程 php手册 ThinkPay's latest WeChat payment official account payment driver sharing

ThinkPay's latest WeChat payment official account payment driver sharing

Dec 01, 2016 am 12:00 AM

ThinkPay’s latest WeChat payment official account payment driver sharing
Let’s share the WeChat payment driver of ThinkPay for everyone’s convenience. If you have any questions, please join the QQ group discussion 105108204<?php<br /> // +-------------------------------------------------- -----------------------<br /> // | Zero Cloud [Simple, Efficient and Excellent]<br /> // +-------------------------------------------------- -----------------------<br /> // | Copyright (c) 2016 http://www.lingyun.net All rights reserved.<br /> // +-------------------------------------------------- -----------------------<br /> // | Author: jry <598821125@qq.com><br> // +-------------------------------------------------- -----------------------<br> namespace AddonsPayThinkPayPayDriver;<br> <br> /**<br> * WeChat payment driver<br> ​*/<br> class Wxpay extends AddonsPayThinkPayPayPay<br> {<br> Protected $gateway = 'https://api.mch.weixin.qq.com/pay/unifiedorder';<br> Protected $orderquery = 'https://api.mch.weixin.qq.com/pay/orderquery';<br> protected $config = array(<br>                                                                                                                                                  'appsecret' => '',<br> ‘mchid’ => '',<br>                                                                                                                                                                   );<br> <br> Public function check()<br> {<br> if (!$this->config['appid'] || !$this->config['appsecret'] || !$this->config['mchid'] || !$this-> config['key']) {<br> E("WeChat payment settings are wrong!");<br>          }<br>           return true;<br> }<br> <br> Public function buildRequestForm($pay_data)<br> {<br>              // APP payment<br> If (C('IS_API')) {<br>               $param = array(<br>                 'appid'                                                                                                                                                                                                                                                                since                'mch_id'                                                                                                                                                                                               since                'nonce_str'                                                                                                                                                                                                                                                                      because                 'body'                                                                                                                                                                                                  because                 'out_trade_no'                                                                                                                                                                                                                                                                                                   'total_fee'                                                                                                                                                                                                                                             'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],<br> 'Notify_url' = & gt; $ this-& gt; config ['notify_url'], <br>                  'trade_type'                                                                                                                                                                                                                because);<br> <br>                                                                                                         $param['sign'] = $this->MakeSign($param);<br>                                                                                                                                                                                         $result = $this->FromXml($this->postXmlCurl($xml_param, $this->gateway));<br> If ($result['return_code'] === 'SUCCESS') {<br> If ($this->CheckSign($result)) {<br>                            // The unified ordering interface returns the normal prepay_id, and then regenerates the signature according to the signature specification, and then transmits the data to the APP. <br> // Participate in the signature field is appid, partnerid, prepayid, noncestr, timestamp, package. Note: The value format of package is Sign=WXPay<br> $prepayparams = array();<br>                         $prepayparams['appid']                                                                                                                                      $prepayparams['partnerid'] = $result['mch_id'];<br>                      $prepayparams['prepayid'] = $result['prepay_id'];<br>                      $prepayparams['noncestr'] = $result['nonce_str'];<br>                                        $prepayparams['package']                                                                                                                              $prepayparams['timestamp'] = time();<br>                           $prepayparams['sign']                                                                                                                                                                                                                                                                               $return['json']                                                                                            Return                  }<br>              }<br>                                        else {<br>                              // Obtain user openId, WeChat public account JSAPI payment is required <br>               $openId = $this->GetOpenid();<br>                  $param = array(<br>                 'appid'                                                                                                                                                                                                                                                                since                'mch_id'                                                                                                                                                                                               since                'nonce_str'        => $this->getNonceStr(),<br>                 'body'             => $pay_data['body'],<br>                 'out_trade_no'     => $pay_data['out_trade_no'],<br>                 'total_fee'        => $pay_data['money'] * 100,<br>                 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],<br>                 'notify_url'       => $this->config['notify_url'],<br>                 'trade_type'       => 'JSAPI',<br>                 'openid'           => $openId,<br>             );<br> <br>             // 签名<br>             $param['sign'] = $this->MakeSign($param);<br>             $xml_param     = $this->ToXml($param);<br>             $result        = $this->FromXml($this->postXmlCurl($xml_param, $this->gateway));<br>             if ($result['return_code'] === 'SUCCESS') {<br>                 if ($this->CheckSign($result)) {<br>                     // 获取JSAPI所需参数<br>                     $jsApiParameters = $this->GetJsApiParameters($result);<br>                     $pay_page        = <<<EOF<br />                         <html><br>                             <head><br>                                 <meta http-equiv="content-type" content="text/html;charset=utf-8"/><br>                                 <meta name="viewport" content="width=device-width, initial-scale=1"/><br>                                 <title>微信支付</title><br>                                 <script type="text/javascript"><br>                                                                                                                                                    function jsApiCall()<br>                                                                                         WeixinJSBridge.invoke(<br> ‘getBrandWCPayRequest’,<br>                                                                                          function(res){<br> WeixinJSBridge.log(res.err_msg);<br>                                                                                                                                           in                                                                                                );<br>                                                                   <br> function callpay()<br>                                                                                         If (typeof WeixinJSBridge == "undefined"){<br> If(document.addEventListener){<br> document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);<br> } Else if (document.attachevent) {<br>                                             document.attachEvent('WeixinJSBridgeReady', jsApiCall);<br>                                             document.attachEvent('onWeixinJSBridgeReady', jsApiCall);<br>                                         }<br>                                     }else{<br>                                         jsApiCall();<br>                                     }<br>                                 }<br>                                 </script><br>                             </head><br>                             <body><br>                                 <br/><br>                                 <font color="#9ACD32"><b>该笔订单支付金额为<span style="color:#f00;font-size:50px">{$pay_data['money']}</span>元</b></font><br/><br/><br>                                 <div align="center"><br>                                     <button style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer; color:white; font-size:16px;" type="button" onclick="callpay()" >立即支付</button><br>                                 </div><br>                                                                                                                                                                                                       EOF;<br>                                                                                                                                                                                                                                    }<br>                     } else {<br> E("WeChat order error!" . $result['return_msg']);<br>             }<br>          }<br> }<br> <br> /**<br> * * Asynchronous notification verification<br> ​​*/<br> Public function verifyNotify($notify)<br> {<br> ​​​​//Get notification data<br> If ($notify['return_code'] === 'SUCCESS') {<br> If (!array_key_exists("transaction_id", $notify)) {<br> E("The input parameters are incorrect!");<br>             }<br>              $param['transaction_id'] = $notify["transaction_id"];<br>                $param['appid']                                                                                                       $param['mch_id']                                                                                                                              $param['nonce_str']                                                                                                                                                                                                       $param['sign']                                                                                                                                                                                                                                     $xml_param                                                                                                                                                                            $result = $this->FromXml($this->postXmlCurl($xml_param, $this->orderquery));<br> If ($this->CheckSign($result)) {<br>               $result['status'] = ($result['result_code'] == 'SUCCESS') ? true : false;<br>                $result['money'] = $result['total_fee'] / 100;<br>                                    $this->info                                                                                                                                                            return true;<br>             }<br>                                       else {<br> E('Notification error');<br>          }<br> }<br> <br> /**<br> *<br> * Get the parameters of jsapi payment<br> * @param array $UnifiedOrderResult Data returned by the unified payment interface<br> * @throws WxPayException<br>     *<br>      * @return json数据,可直接填入js函数作为参数<br>      */<br>     public function GetJsApiParameters($UnifiedOrderResult)<br>     {<br>         if (!array_key_exists("appid", $UnifiedOrderResult)<br>             || !array_key_exists("prepay_id", $UnifiedOrderResult)<br>             || $UnifiedOrderResult['prepay_id'] == "") {<br>             E("参数错误");<br>         }<br>         $jsapi['appId']     = $UnifiedOrderResult["appid"];<br>         $jsapi['timeStamp'] = (string) time();<br>         $jsapi['nonceStr']  = $this->getNonceStr();<br>         $jsapi['appId']     = $UnifiedOrderResult["appid"];<br>         $jsapi['package']   = "prepay_id=" . $UnifiedOrderResult['prepay_id'];<br>         $jsapi['signType']  = 'MD5';<br>         $jsapi['paySign']   = $this->MakeSign($jsapi);<br>         $parameters         = json_encode($jsapi);<br>         return $parameters;<br>     }<br> <br>     /**<br> * Submit xml to the corresponding interface url in post mode<br> *<br> * @param string $xml XML data required for post<br> * @param string $url url<br> * @param bool $useCert Whether a certificate is required, not required by default<br> * @param int $second URL execution timeout, default 30s<br> * @throws WxPayException<br> ​​*/<br>     private static function postXmlCurl($xml, $url, $useCert = false, $second = 30)<br>     {<br>         $ch = curl_init();<br>         //设置超时<br>         curl_setopt($ch, CURLOPT_TIMEOUT, $second);<br> <br>         //如果有配置代理这里就设置代理<br>         // if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"<br>         //             && WxPayConfig::CURL_PROXY_PORT != 0){<br>         //             curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);<br>         //             curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);<br>         //         }<br>         curl_setopt($ch, CURLOPT_URL, $url);<br>         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);<br>         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //严格校验<br>         //设置header<br>         curl_setopt($ch, CURLOPT_HEADER, false);<br>         //要求结果为字符串且输出到屏幕上<br>        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br> <br>           if ($useCert == true) {<br>                                                                                                                                                                                                                                to set up the certificate <br>                    //Use certificate: cert and key belong to two .pem files respectively<br>              curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');<br>               curl_setopt($ch, CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH);<br>               curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');<br>               curl_setopt($ch, CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH);<br>         }<br>             //Post submission method<br>         curl_setopt($ch, CURLOPT_POST, true);<br>         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);<br> ​​​​//Run curl<br> ​​​​$data = curl_exec($ch);<br>                  //Return the result<br>           if ($data) {<br>                 curl_close($ch);<br>                                                                                                                                                                                                                                                                               return  $data;<br>                                        else {<br>                $error = curl_errno($ch);<br>                 curl_close($ch);<br> E("curl error, error code: $error");<br>         }<br> }<br> <br> /*<br> * * Generate a random string, no longer than 32 bits<br> * @param int $length<br> * * @return Random string generated<br> */<br> Public static function getNonceStr($length = 32)<br> {<br> ​​​​$chars = "abcdefghijklmnopqrstuvwxyz0123456789";<br>          $str                                                                                                             for ($i = 0; $i < $length; $i++) {<br />               $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);<br />         }<br /> Return $ Str; <br /> }<br /> <br /> /**<br /> * Generate signature<br /> * @return Signature, this function does not cover the sign member variable. If you want to set the signature, you need to call the SetSign method to assign a value<br /> ​​*/<br /> Public function MakeSign($param)<br /> {<br /> ​​​​//Signature step 1: Sort parameters in dictionary order<br />          ksort($param);<br />          $string = $this->ToUrlParams($param);<br> ​​​​//Signature step 2: Add KEY after the string<br> $string = $string . "&key=" . $this->config['key'];<br> ​​​​//Signature step three: MD5 encryption<br>         $string = md5($string);<br> ​​​​ //Signature step 4: Convert all characters to uppercase<br>          $result = strtoupper($string);<br> Return $ result; <br> }<br> <br> /**<br> *<br>     * 检测签名<br>      */<br>     public function CheckSign($param)<br>     {<br>         $sign = $this->MakeSign($param);<br>         if ($param['sign'] == $sign) {<br>             return true;<br>         } else {<br>             E("签名错误!");<br>         }<br>     }<br> <br>     /**<br> *<br> * * Splicing signature string<br> * @param array $urlObj<br> *<br> * @return Returns the concatenated string<br> ​​*/<br>     public function ToUrlParams($param)<br>     {<br>         $buff = "";<br>         foreach ($param as $k => $v) {<br>             if ($k != "sign" && $v != "" && !is_array($v)) {<br>                 $buff .= $k . "=" . $v . "&";<br>             }<br>         }<br> <br>         $buff = trim($buff, "&");<br>         return $buff;<br>     }<br> <br>     /**<br> * Output xml characters <br> * @throws WxPayException<br> **/<br>     public function ToXml($param)<br>     {<br>         if (!is_array($param)<br>             || count($param) <= 0) {<br />             E("数组数据异常!");<br />         }<br /> <br />         $xml = "<xml>";<br>         foreach ($param as $key => $val) {<br>             if (is_numeric($val)) {<br>                 $xml .= "<" . $key . ">" . $val . "</" . $key . ">";<br>             } else {<br>                 $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";<br>             }<br>         }<br>         $xml .= "</xml>";<br>         return $xml;<br>     }<br> <br>     /**<br> * Convert xml to array<br> * * @param string $xml<br> * @throws WxPayException<br> ​​*/<br>     public function FromXml($xml)<br>     {<br>         if (!$xml) {<br>             E("xml数据异常!");<br>         }<br>​​​​//Convert XML to array<br> ​​​​//It is forbidden to reference external xml entities<br> ​​​​libxml_disable_entity_loader(true);<br>          $this->values ​​= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);<br>            return $this->values;<br> }<br> <br> /**<br> *<br> * Get the user’s openid through jump. The jump process is as follows: <br> * 1. Set the URL and other parameters you need to call back, and jump to the WeChat server https://open.weixin.qq.com/connect/oauth2/authorize<br> * 2. After the WeChat service processing is completed, it will jump back to the user redirect_uri address. At this time, some parameters will be brought, such as: code<br> *<br> * @return User’s openid<br> ​​*/<br> Public function GetOpenid()<br> {<br> ​​​​//Get openid through code<br> If (!isset($_GET['code'])) {<br> //Trigger WeChat return code<br> $baseUrl = urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);<br>                 $url                                                                                                                                                                                                                 Header("Location: $url");<br> exit();<br>                                        else {<br>                                                                                                                                                                                                                                                         to get the code to get the openid<br>                  $code                                                                                                                                                    $openid = $this->getOpenidFromMp($code);<br>                   return $openid;<br>         }<br> }<br> <br> /**<br> *<br> * Get the openid machine access_token from the work platform through code<br> * @param string $code The code brought back by WeChat<br> *<br> * * @return openid<br> ​​*/<br> Public function GetOpenidFromMp($code)<br> {<br>          $url = $this->__CreateOauthUrlForOpenid($code);<br> ​​​​//Initialize curl<br>          $ch = curl_init();<br> ​​​​//Set timeout<br>          curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);<br>         curl_setopt($ch, CURLOPT_URL, $url);<br>         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);<br>         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);<br>         curl_setopt($ch, CURLOPT_HEADER, false);<br>         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br> ​​​​///if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"<br>                                                                                                                                                                       curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);<br>        //             curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);<br>         //         }<br>         //运行curl,结果以jason形式返回<br>         $res = curl_exec($ch);<br>         curl_close($ch);<br>         //取出openid<br>         $data       = json_decode($res, true);<br>         $this->data = $data;<br>         $openid     = $data['openid'];<br>         return $openid;<br>     }<br> <br>     /**<br> *<br> * Construct the url connection to obtain the code<br> * @param string $redirectUrl The url that the WeChat server bounces back, requires url encoding<br> *<br> * @return Return the constructed url<br> ​​*/<br>     private function __CreateOauthUrlForCode($redirectUrl)<br>     {<br>         $urlObj["appid"]         = $this->config['appid'];<br>         $urlObj["redirect_uri"]  = "$redirectUrl";<br>         $urlObj["response_type"] = "code";<br>         $urlObj["scope"]         = "snsapi_base";<br>         $urlObj["state"]         = "#wechat_redirect";<br>         $bizString               = $this->ToUrlParams($urlObj);<br>         return "https://open.weixin.qq.com/connect/oauth2/authorize?" . $bizString;<br>     }<br> <br>     /**<br> *<br> * Construct to obtain the url address of open and access_toke<br> * @param string $code, the code brought back by WeChat jump<br> *<br> * @return requested url<br> ​​*/<br>     private function __CreateOauthUrlForOpenid($code)<br>     {<br>         $urlObj["appid"]      = $this->config['appid'];<br>         $urlObj["secret"]     = $this->config['appsecret'];<br>         $urlObj["code"]       = $code;<br>         $urlObj["grant_type"] = "authorization_code";<br>         $bizString            = $this->ToUrlParams($urlObj);<br>         return "https://api.weixin.qq.com/sns/oauth2/access_token?" . $bizString;<br>     }<br> }

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Learn about introductory code examples for Python programming Learn about introductory code examples for Python programming Jan 04, 2024 am 10:50 AM

Learn about Python programming with introductory code examples Python is an easy-to-learn, yet powerful programming language. For beginners, it is very important to understand the introductory code examples of Python programming. This article will provide you with some concrete code examples to help you get started quickly. Print HelloWorldprint("HelloWorld") This is the simplest code example in Python. The print() function is used to output the specified content

PHP variables in action: 10 real-life examples of use PHP variables in action: 10 real-life examples of use Feb 19, 2024 pm 03:00 PM

PHP variables store values ​​during program runtime and are crucial for building dynamic and interactive WEB applications. This article takes an in-depth look at PHP variables and shows them in action with 10 real-life examples. 1. Store user input $username=$_POST["username"];$passWord=$_POST["password"]; This example extracts the username and password from the form submission and stores them in variables for further processing. 2. Set the configuration value $database_host="localhost";$database_username="username";$database_pa

From beginner to proficient: Code implementation of commonly used data structures in Go language From beginner to proficient: Code implementation of commonly used data structures in Go language Mar 04, 2024 pm 03:09 PM

Title: From Beginner to Mastery: Code Implementation of Commonly Used Data Structures in Go Language Data structures play a vital role in programming and are the basis of programming. In the Go language, there are many commonly used data structures, and mastering the implementation of these data structures is crucial to becoming a good programmer. This article will introduce the commonly used data structures in the Go language and give corresponding code examples to help readers from getting started to becoming proficient in these data structures. 1. Array Array is a basic data structure, a group of the same type

How to use PHP to write inventory management function code in the inventory management system How to use PHP to write inventory management function code in the inventory management system Aug 06, 2023 pm 04:49 PM

How to use PHP to write the inventory management function code in the inventory management system. Inventory management is an indispensable part of many enterprises. For companies with multiple warehouses, the inventory management function is particularly important. By properly managing and tracking inventory, companies can allocate inventory between different warehouses, optimize operating costs, and improve collaboration efficiency. This article will introduce how to use PHP to write code for inventory warehouse management functions, and provide you with relevant code examples. 1. Establish the database before starting to write the code for the inventory warehouse management function.

Java implements simple bubble sort code Java implements simple bubble sort code Jan 30, 2024 am 09:34 AM

The simplest code example of Java bubble sort Bubble sort is a common sorting algorithm. Its basic idea is to gradually adjust the sequence to be sorted into an ordered sequence through the comparison and exchange of adjacent elements. Here is a simple Java code example that demonstrates how to implement bubble sort: publicclassBubbleSort{publicstaticvoidbubbleSort(int[]arr){int

Go language programming examples: code examples in web development Go language programming examples: code examples in web development Mar 04, 2024 pm 04:54 PM

"Go Language Programming Examples: Code Examples in Web Development" With the rapid development of the Internet, Web development has become an indispensable part of various industries. As a programming language with powerful functions and superior performance, Go language is increasingly favored by developers in web development. This article will introduce how to use Go language for Web development through specific code examples, so that readers can better understand and use Go language to build their own Web applications. 1. Simple HTTP Server First, let’s start with a

Huawei Cloud Edge Computing Interconnection Guide: Java code examples to quickly implement interfaces Huawei Cloud Edge Computing Interconnection Guide: Java code examples to quickly implement interfaces Jul 05, 2023 pm 09:57 PM

Huawei Cloud Edge Computing Interconnection Guide: Java Code Samples to Quickly Implement Interfaces With the rapid development of IoT technology and the rise of edge computing, more and more enterprises are beginning to pay attention to the application of edge computing. Huawei Cloud provides edge computing services, providing enterprises with highly reliable computing resources and a convenient development environment, making edge computing applications easier to implement. This article will introduce how to quickly implement the Huawei Cloud edge computing interface through Java code. First, we need to prepare the development environment. Make sure you have the Java Development Kit installed (

Guidance and Examples: Learn to implement the selection sort algorithm in Java Guidance and Examples: Learn to implement the selection sort algorithm in Java Feb 18, 2024 am 10:52 AM

Java Selection Sorting Method Code Writing Guide and Examples Selection sorting is a simple and intuitive sorting algorithm. The idea is to select the smallest (or largest) element from the unsorted elements each time and exchange it until all elements are sorted. This article will provide a code writing guide for selection sorting, and attach specific Java sample code. Algorithm Principle The basic principle of selection sort is to divide the array to be sorted into two parts, sorted and unsorted. Each time, the smallest (or largest) element is selected from the unsorted part and placed at the end of the sorted part. Repeat the above

See all articles