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

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 <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        =                          <br>                             <br>                                 <meta> <br>                                 <meta> <br>                                 <title>微信支付</title> <br>                                 <script><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(&#039;WeixinJSBridgeReady&#039;, jsApiCall);<br /> document.attachEvent(&#039;onWeixinJSBridgeReady&#039;, jsApiCall);<br /> }<br /> }else{<br /> jsApiCall();<br /> }<br /> }<br /> </script><br>                             <br>                             <br>                                 <br><br>                                 <font><b>该笔订单支付金额为<span>{$pay_data['money']}</span>元</b></font><br><br><br>                                 <div> <br>                                     <button>立即支付</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               $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)              E("数组数据异常!");<br>         }<br> <br>         $xml = "<xml>";<br>         foreach ($param as $key => $val) {<br>             if (is_numeric($val)) {<br>                 $xml .= "" . $val . "" . $key . ">";<br>             } else {<br>                 $xml .= "" . $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
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
了解Python编程的入门级代码示例了解Python编程的入门级代码示例Jan 04, 2024 am 10:50 AM

了解Python编程的入门级代码示例Python是一种简单易学,功能强大的编程语言。对于初学者来说,了解Python编程的入门级代码示例是非常重要的。本文将为您提供一些具体的代码示例,帮助您快速入门。打印HelloWorldprint("HelloWorld")这是Python中最简单的代码示例。print()函数用于将指定的内容输出

PHP переменные в действии: 10 реальных примеров использованияPHP переменные в действии: 10 реальных примеров использованияFeb 19, 2024 pm 03:00 PM

PHP变量存储程序运行期间的值,对于构建动态且交互式的WEB应用程序至关重要。本文将深入探讨php变量,并通过10个真实的示例展示它们的实际应用。1.存储用户输入$username=$_POST["username"];$passWord=$_POST["password"];此示例从表单提交中提取用户名和密码,并将其存储在变量中以供进一步处理。2.设置配置值$database_host="localhost";$database_username="username";$database_pa

从入门到精通:Go语言中常用数据结构的代码实现从入门到精通:Go语言中常用数据结构的代码实现Mar 04, 2024 pm 03:09 PM

标题:从入门到精通:Go语言中常用数据结构的代码实现数据结构在编程中起着至关重要的作用,它是程序设计的基础。在Go语言中,有许多常用的数据结构,掌握这些数据结构的实现方式对于成为一名优秀的程序员至关重要。本文将介绍Go语言中常用的数据结构,并给出相应的代码示例,帮助读者从入门到精通这些数据结构。1.数组(Array)数组是一种基本的数据结构,是一组相同类型

Java实现简单的冒泡排序代码Java实现简单的冒泡排序代码Jan 30, 2024 am 09:34 AM

Java冒泡排序最简单的代码示例冒泡排序是一种常见的排序算法,它的基本思想是通过相邻元素的比较和交换来将待排序序列逐步调整为有序序列。下面是一个简单的Java代码示例,演示了如何实现冒泡排序:publicclassBubbleSort{publicstaticvoidbubbleSort(int[]arr){int

Go语言编程实例:Web开发中的代码示例Go语言编程实例:Web开发中的代码示例Mar 04, 2024 pm 04:54 PM

《Go语言编程实例:Web开发中的代码示例》随着互联网的快速发展,Web开发已经成为各行业中必不可少的一部分。作为一门功能强大且性能优越的编程语言,Go语言在Web开发中越来越受到开发者们的青睐。本文将通过具体的代码示例,介绍如何利用Go语言进行Web开发,让读者能够更好地理解和运用Go语言来构建自己的Web应用。1.简单的HTTP服务器首先,让我们从一个

如何使用PHP编写库存管理系统中的库存分仓管理功能代码如何使用PHP编写库存管理系统中的库存分仓管理功能代码Aug 06, 2023 pm 04:49 PM

如何使用PHP编写库存管理系统中的库存分仓管理功能代码库存管理是许多企业中不可或缺的一部分。对于拥有多个仓库的企业来说,库存分仓管理功能尤为重要。通过合理管理和跟踪库存,企业可以实现不同仓库之间的库存调拨,优化运营成本,改善协同效率。本文将介绍如何使用PHP编写库存分仓管理功能的代码,并为您提供相关的代码示例。一、建立数据库在开始编写库存分仓管理功能的代码之

指导与示例:学习Java选择排序算法的实现指导与示例:学习Java选择排序算法的实现Feb 18, 2024 am 10:52 AM

Java选择排序法代码编写指南及示例选择排序是一种简单直观的排序算法,其思想是每次从未排序的元素中选择最小(或最大)的元素进行交换,直到所有元素排序完成。本文将提供选择排序的代码编写指南,并附上具体的Java示例代码。算法原理选择排序的基本原理是将待排序数组分为已排序和未排序两部分,每次从未排序部分选择最小(或最大)的元素,将其放到已排序部分的末尾。重复上述

华为云边缘计算对接指南:Java代码示例快速实现接口华为云边缘计算对接指南:Java代码示例快速实现接口Jul 05, 2023 pm 09:57 PM

华为云边缘计算对接指南:Java代码示例快速实现接口随着物联网技术的快速发展和边缘计算的兴起,越来越多的企业开始关注边缘计算的应用。华为云提供了边缘计算服务,为企业提供了高可靠的计算资源和便捷的开发环境,使得边缘计算应用更加容易实现。本文将介绍如何通过Java代码快速实现华为云边缘计算的接口。首先,我们需要准备好开发环境。确保你已经安装了Java开发工具包(

See all articles

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

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor