PHP implements WeChat payment function development code sharing

小云云
Release: 2023-03-21 06:46:02
Original
6438 people have browsed it

This article mainly introduces the development process of PHP WeChat payment in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

1. Development environment
Thinkphp 3.2.3
WeChat: Service account, certified
Development domain name: http://test.paywechat.com (since The defined domain name is not accessible from the external network)

2. Requires relevant documents and permissions
WeChat payment needs to be activated
WeChat public platform developer documentation: http:// mp.weixin.qq.com/wiki/home/index.html
WeChat Payment Developer Documentation: https://pay.weixin.qq.com/wiki/doc/api/index.html
WeChat Payment SDK download address: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1

3. Development
Download WeChat To pay for the PHP version of the SDK, the file directory is as shown below:

PHP implements WeChat payment function development code sharing

PHP implements WeChat payment function development code sharing

Put the Cert and Lib directories of the WeChat payment SDK Thinkphp, the directory is

PHP implements WeChat payment function development code sharing

Now we will introduce the WeChat payment authorization directory issue. The first is to fill in the payment authorization directory in the WeChat payment development configuration,

PHP implements WeChat payment function development code sharing

Then fill in the js interface security domain.

PHP implements WeChat payment function development code sharing

Finally set the web page authorization

PHP implements WeChat payment function development code sharing

PHP implements WeChat payment function development code sharing

After these settings are completed, it is basically half completed. Pay attention to the set directory and the directory in my thinkphp.

PHP implements WeChat payment function development code sharing

4. WeChat payment configuration

PHP implements WeChat payment function development code sharing

Fill in the relevant configuration correctly.




##[php]view plaincopy


  1. ##/**

  2. ##* Configure account information

  3. */

  4. ##classWxPayConfig

  5. ##{

  6. //========[Basic information settings]==================== =================

  7. //

  8. /**

  9. * TODO: Modify the configuration here to apply for your own merchant information

  10. * WeChat public account information configuration

  11. ## *

  12. ## * APPID : APPID bound to payment (must be configured, can be viewed in the account opening email)
  13. *
  14. * MCHID: Merchant ID (must be configured, can be viewed in the account opening email)
  15. *
  16. * KEY: Merchant payment key, refer to the account opening email settings (must be configured, log in to the merchant platform to set it yourself )
  17. * Setting address: https://pay.weixin.qq.com/index.php/account/api_cert
  18. ## *
  19. ## * APPSECRET: Public account secert (only required for JSAPI payment, log in to the public platform and enter the developer center to set),

  20. ## * Obtain address: https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=2005451881&lang=zh_CN

  21. * @var string

  22. ## */

  23. constAPPID ='';

  24. ##const

    MCHID ='';

  25. ##const
  26. KEY ='';

  27. const
  28. APPSECRET ='';

  29. ##//=======【 Certificate path settings】======================================
  30. /**
  31. * TODO :Set the merchant certificate path
  32. * Certificate path, please note that the absolute path should be filled in (only required for refunds and order cancellations, you can log in Merchant platform download,
  33. * API certificate download address: https://pay.weixin.qq.com/index.php/account/api_cert, you need to install the merchant operation certificate before downloading)

  34. ## * @var path

  35. */

  36. constSSLCERT_PATH ='. ./cert/apiclient_cert.pem';

  37. constSSLKEY_PATH ='../cert/apiclient_key.pem';

  38. ##//========[curl proxy settings]======================== ============

  39. ##/**

  40. ## * TODO: Set the proxy machine here. Set it only when you need a proxy. If you don’t need a proxy, please set it to 0.0.0.0 and 0
  41. ## * This routine uses the HTTP POST method through curl. The proxy server can be modified here,
  42. * The default is CURL_PROXY_HOST=0.0.0.0 and CURL_PROXY_PORT=0, the proxy is not enabled at this time (set it if necessary)
  43. * @var unknown_type
  44. ##*/

  45. constCURL_PROXY_HOST ="0.0.0.0";// "10.152.18.220";

  46. ##constCURL_PROXY_PORT = 0;//8080;

  47. ##//========[Report information configuration]================================== ====

  48. ##/**

  49. * TODO: Interface call reporting level, default error reporting (note: reporting timeout is [1s], reporting regardless of success or failure [Never throw an exception],

  50. * Will not affect the interface calling process), after turning on the reporting, it is convenient for WeChat monitoring request calls For quality, it is recommended to at least

  51. * Enable error reporting.

  52. ## * Reporting level, 0. Close reporting; 1. Only errors are reported; 2. Full reporting
  53. * @var int
  54. ##*/
  55. const
  56. REPORT_LEVENL = 1;

    }

Start posting the code now:




# #[php]view plaincopy


  1. ##namespace Wechat\ Controller;

  2. ##use

    Think\Controller;

  3. /**

  4. ## * Parent class controller, need to inherit
  5. * @file ParentController.class.php
  6. ## * @author Gary
  7. # * @date August 4, 2015

  8. * @todu

  9. */

  10. ##classParentControllerextendsController {

  11. protected$options=array(

  12. 'token'=>'',// Fill in the key you set

  13. ##'encodingaeskey'=>'',// Fill in the EncodingAESKey for encryption

  14. 'appid'=>'',// Fill in the advanced The app idof the calling function

  15. ##'appsecret'

    =>'',// Fill in the key for the advanced calling function

  16. 'debug'=> false,

  17. 'logcallback'=>''

  18. );

  19. public$errCode= 40001;

  20. public$errMsg="no access";

  21. /**

  22. * 获取access_token

  23. * @return mixed|boolean|unknown

  24. */

  25. publicfunctiongetToken(){

  26. $cache_token= S('exp_wechat_pay_token');

  27. if(!empty($cache_token)){

  28. return$cache_token;

  29. }

  30. $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';

  31. $url= sprintf($url,$this->options['appid'],$this->options['appsecret']);

  32. $result=$this->http_get($url);

  33. $result= json_decode($result,true);

  34. if(empty($result)){

  35. returnfalse;

  36. }

  37. S('exp_wechat_pay_token',$result['access_token'],array('type'=>'file','expire'=>3600));

  38. return$result['access_token'];

  39. }

  40. /**

  41. ## * Send customer service message

  42. * @param array $data Message structure {"touser":"OPENID","msgtype":"news","news":{...}}

  43. */

  44. publicfunctionsendCustomMessage($data){

  45. $token=$this->getToken();

  46. if(empty($token))returnfalse;

  47. $url='https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s';

  48. $url= sprintf($url,$token);

  49. $result=$this->http_post($url,self::json_encode($data));

  50. if($result)

  51. {

  52. $json= json_decode($result,true);

  53. if(!$json|| !empty($json['errcode'])) {

  54. $this->errCode =$json['errcode'];

  55. #$this->errMsg =$json['errmsg'];

  56. #returnfalse;

  57. }

  58. return$json;

  59. }

  60. returnfalse;

  61. }

  62. #

  63. /**

  64. ## * Send template message

  65. * @param unknown $data

  66. ## * @return boolean|unknown

  67. */

  68. publicfunctionsendTemplateMessage($data){

  69. $token=$this->getToken();

  70. if(empty($token))returnfalse;

  71. $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";

  72. $url= sprintf($url,$token);

  73. $result=$this->http_post($url,self::json_encode($data));

  74. if($result)

  75. {

  76. $json= json_decode($result,true);

  77. if(!$json|| !empty($json['errcode'])) {

  78. $this->errCode =$json['errcode'];

  79. #$this->errMsg =$json['errmsg'];

  80. #returnfalse;

  81. }

  82. return$json;

  83. }

  84. returnfalse;

  85. }

  86. #

  87. publicfunctiongetFileCache($name){

  88. returnS($name);

  89. }

  90. /**

  91. ## * WeChat API does not support Chinese escaped json structure

  92. * @param array $arr

  93. */

  94. staticfunctionjson_encode($arr) {

  95. $parts=array();

  96. $is_list= false;

  97. //Find out if the given array is a numerical array

  98. $keys=array_keys($arr);

  99. $max_length=count($arr) - 1;

  100. if(($keys[0] === 0) && ($keys[$max_length] ===$max_length)) {//See if the first key is 0 and last key is length - 1

  101. $is_list= true;

  102. for($i= 0;$icount($keys);$i++) {//See if each key correspondes to its position

  103. if($i!=$keys[$i]) {//A key fails at position check.

  104. $is_list= false;//It is an associative array.

  105. break;

  106. }

  107. }

  108. }

  109. foreach($arras$key=>$value) {

  110. if(is_array($value)) {//Custom handling for arrays

  111. if($is_list)

  112. $parts[] = self::json_encode ($value);/* :RECURSION: */

  113. else

  114. $parts[] ='"'.$key.'":'. self::json_encode ($value);/* :RECURSION: */

  115. }else{

  116. $str='';

  117. if(!$is_list)

  118. $str='"'.$key.'":';

  119. //Custom handling for multiple data types

  120. if(!is_string($value) &&is_numeric($value) &&$value

  121. $str.=$value;//Numbers

  122. elseif($value=== false)

  123. $str.='false';//The booleans

  124. elseif($value=== true)

  125. $str.='true';

  126. else

  127. $str.='"'.addslashes($value) .'"';//All other things

  128. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)

  129. $parts[] =$str;

  130. }

  131. }

  132. $json= implode (',',$parts);

  133. if($is_list)

  134. return'['.$json.']';//Return numerical JSON

  135. ##return'{'.$json.'}';//Return associative JSON

  136. }

  137. /**

  138. +--------------------------------- ----------------------------

  139. * Generate random string

  140. +------------------ ----------------------------------------

  141. * @param int $length The length of the random string to be generated

  142. * @param string $type Random code type: 0, numbers + upper and lower case letters; 1, numbers; 2, lower case letters; 3, upper case letters; 4, special characters; -1, numbers + upper and lower case letters + special characters

  143. +----------------------------------------------------------

  144. * @return string

  145. +----------------------------------------------------------

  146. */

  147. staticpublicfunctionrandCode($length= 5,$type= 2){

  148. $arr=array(1 =>"0123456789", 2 =>"abcdefghijklmnopqrstuvwxyz", 3 =>"ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 =>"~@#$%^&*(){}[]|");

  149. if($type== 0) {

  150. array_pop($arr);

  151. $string= implode("",$arr);

  152. }elseif($type=="-1") {

  153. $string= implode("",$arr);

  154. }else{

  155. $string=$arr[$type];

  156. }

  157. $count=strlen($string) - 1;

  158. $code='';

  159. for($i= 0;$i$length;$i++) {

  160. $code.=$string[rand(0,$count)];

  161. }

  162. return$code;

  163. }

  164. /**

  165. * GET 请求

  166. * @param string $url

  167. */

  168. privatefunctionhttp_get($url){

  169. $oCurl= curl_init();

  170. if(stripos($url,"https://")!==FALSE){

  171. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);

  172. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);

  173. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1);//CURL_SSLVERSION_TLSv1

  174. }

  175. curl_setopt($oCurl, CURLOPT_URL,$url);

  176. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );

  177. $sContent= curl_exec($oCurl);

  178. $aStatus= curl_getinfo($oCurl);

  179. curl_close($oCurl);

  180. if(intval($aStatus["http_code"])==200){

  181. return$sContent;

  182. }else{

  183. returnfalse;

  184. }

  185. }

  186. /**

  187. ## * POST request

  188. # # * @param string $url

  189. ## * @param array $param

  190. * @param boolean $post_file Whether to upload files

  191. ## * @return string content
  192. */
  193. private
  194. functionhttp_post($url,$param,$post_file=false){

  195. $oCurl
  196. = curl_init();

  197. if(stripos($url,"https://")!==FALSE){

  198. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);

  199. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);

  200. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1);//CURL_SSLVERSION_TLSv1

  201. }

  202. if(is_string($param) ||$post_file) {

  203. $strPOST=$param;

  204. }else{

  205. $aPOST=array();

  206. foreach($paramas$key=>$val){

  207. $aPOST[] =$key."=".urlencode($val);

  208. }

  209. $strPOST= join("&",$aPOST);

  210. }

  211. curl_setopt($oCurl, CURLOPT_URL,$url);

  212. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );

  213. curl_setopt($oCurl, CURLOPT_POST,true);

  214. curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);

  215. $sContent= curl_exec($oCurl);

  216. $aStatus= curl_getinfo($oCurl);

  217. curl_close($oCurl);

  218. if(intval($aStatus["http_code"])==200){

  219. return$sContent;

  220. }else{

  221. returnfalse;

  222. }

  223. }

  224. }




[php]view plaincopy


  1. namespace Wechat\Controller;

  2. useWechat\Controller\ParentController;

  3. /**

  4. ## * WeChat payment test controller

  5. * @file TestController.class.php

  6. ## * @author Gary

  7. ## * @date August 4, 2015

  8. * @todu

  9. */

  10. classTestControllerextendsParentController {

  11. private$_order_body='xxx';

  12. private$_order_goods_tag='xxx';

  13. publicfunction__construct(){

  14. parent::__construct();

  15. require_onceROOT_PATH."Api/lib/WxPay.Api.php";

  16. require_onceROOT_PATH."Api/lib/WxPay.JsApiPay.php";

  17. }

  18. publicfunctionindex(){

  19. //①. Get user openid

  20. ## $tools=new\JsApiPay();

  21. # #$openId=$tools->GetOpenid();

  22. //②. Unified order placement

  23. ##$input

    =new\WxPayUnifiedOrder();

  24. #//Product description
  25. ##$input
  26. ->SetBody(

    $this->_order_body);##//Additional data, you can add the data you need, and WeChat will return an asynchronous callback This data will be appended

  27. $input->SetAttach('xxx');

  28. //Merchant order number

  29. ##$out_trade_no= \WxPayConfig::MCHID.date("YmdHis");

  30. ##$input->SetOut_trade_no($out_trade_no);

  31. #//Total amount, the total amount of the order, can only be an integer, the unit is cents

  32. $input

    ->SetTotal_fee(1);

  33. //Transaction start time

  34. $input

    ->SetTime_start(date("YmdHis"));

  35. //Transaction end time

  36. $input->SetTime_expire(date("YmdHis ", time() + 600));

  37. ##//Product tag

  38. ##$input->SetGoods_tag($this->_order_goods_tag);

  39. #//Notification address, receive WeChat payment asynchronous notification callback address SITE_URL=http://test .paywechat.com/Charge

  40. ##$notify_url
  41. = SITE_URL.'/index.php/Test/notify.html';

  42. $input
  43. ->SetNotify_url($notify_url);

    ##/ /Trade Type
  44. ##$input

  45. ->SetTrade_type(
  46. "JSAPI");##$input

    ->SetOpenid(
  47. $openId

    );

  48. $order= \WxPayApi::unifiedOrder($input);

  49. $jsApiParameters=$tools->GetJsApiParameters($order);

  50. ##//Get the shared delivery address js function parameters

  51. ##$editAddress=$tools->GetEditAddressParameters();

  52. ## $this

    ->assign('openId',$openId);

  53. ##$this
  54. ->assign('jsApiParameters',$jsApiParameters);

    ##$this
  55. ->assign (

    'editAddress',$editAddress);

  56. $this->display();

  57. # # }

  58. #/**

  59. ## * Asynchronous notification callback method

  60. */

  61. public

    functionnotify (){

  62. ##require_once
  63. ROOT_PATH."Api/lib/notify.php ";

    ##$notify
  64. =

    new\PayNotifyCallBack();##$notify

  65. ->Handle(false);
  66. //The IsSuccess here is a method customized by me. I will post the code of this file later for reference.

  67. $is_success

  68. =
  69. $notify->IsSuccess();

  70. $bdata=$is_success['data'];

  71. //支付成功

  72. if($is_success['code'] == 1){

  73. $news=array(

  74. 'touser'=>$bdata['openid'],

  75. 'msgtype'=>'news',

  76. 'news'=>array(

  77. 'articles'=>array(

  78. array(

  79. ##'title'=>'Order payment successful',

  80. ##

    'description'=>"Payment amount: {$bdata['total_fee']}\n".

  81. ##"WeChat order number: {$bdata['transaction_id']}\n"

  82. 'picurl'

    =>'',

  83. 'url'

    =>''

  84. )
  85. ## )
  86. )
  87. ## );

  88. //Send WeChat payment notification

  89. # #$this->sendCustomMessage($news);

  90. }else{//Payment failed

  91. }

  92. ## }

  93. ##/**

  94. ## * Payment success page
  95. * Unreliable callbacks
  96. */
  97. public
  98. functionajax_PaySuccess(){

  99. //Order number
  100. $out_trade_no
  101. = I('post.out_trade_no');

  102. //Payment amount

  103. $ total_fee= I('post.total_fee');

  104. /*Related logic processing*/

  105. ## }

Paste template HTML




##[xhtml]

view plaincopy


  1. #html>
  2. ##

    head>

  3. ##metahttp-equiv="content-type"content="text/html;charset=utf-8"/>

  4. ##metaname="viewport"content="width= device-width, initial-scale=1"/>

  5. ##< ;

    title>WeChat payment sample-paymenttitle>

  6. scripttype="text/javascript">

  7. ## //Call WeChat JS api payment

  8. function jsApiCall()

  9. {

  10. WeixinJSBridge.invoke(

  11. ## 'getBrandWCPayRequest',

  12. {$jsApiParameters},

  13. function(res){

  14. ## WeixinJSBridge.log( res.err_msg);
  15. ## //Cancel payment
  16. ## if(

    res.err_msg
  17. == 'get_brand_wcpay_request:cancel'){

    ## //Event logic for processing payment cancellation

  18. ## }else if(res.err_msg

    == "get_brand_wcpay_request:ok"){
  19. /*Use the above method to determine the front-end return. The WeChat team solemnly reminds:

  20. res.err_msg will be used when the user pays Returns ok after success, but it does not guarantee that it is absolutely reliable

  21. ## Here you can use Ajax to submit to the background and process some logs, such as ajax_PaySuccess in the Test controller. method.

  22. */

  23. }

  24. alert(res.err_code+res.err_desc+res.err_msg);

  25. ## }
  26. );
  27. }

  28. function callpay()

  29. {

  30. if (typeofWeixinJSBridge== "undefined"){

  31. if( document.addEventListener ){

  32. document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);

  33. }else if (document.attachEvent){

  34. document.attachEvent('WeixinJSBridgeReady', jsApiCall);

  35. document.attachEvent('onWeixinJSBridgeReady', jsApiCall);

  36. }

  37. }else{

  38. jsApiCall();

  39. }

  40. }

  41. //获取共享地址

  42. function editAddress()

  43. {

  44. WeixinJSBridge.invoke(

  45. 'editAddress',

  46. {$editAddress},

  47. function(res){

  48. varvalue1=res.proviceFirstStageName;

  49. varvalue2=res.addressCitySecondStageName;

  50. varvalue3=res.addressCountiesThirdStageName;

  51. varvalue4=res.addressDetailInfo;

  52. vartel=res.telNumber;

  53. alert(value1 + value2 + value3 + value4 + ":" + tel);

  54. }

  55. );

  56. }

  57. window.onload=function(){

  58. if (typeofWeixinJSBridge== "undefined"){

  59. if( document.addEventListener ){

  60. document.addEventListener('WeixinJSBridgeReady', editAddress, false);

  61. }else if (document.attachEvent){

  62. document.attachEvent('WeixinJSBridgeReady', editAddress);

  63. document.attachEvent('onWeixinJSBridgeReady', editAddress);

  64. }

  65. }else{

  66. editAddress();

  67. }

  68. };

  69. script>

  70. head>

  71. body>

  72. br/>

  73. fontcolor="#9ACD32">b>The payment amount for this order isspanstyle="color:#f00;font-size:50px">1 pointspan>b>font>< ;br/>br/>

  74. palign="center">

  75. buttonstyle="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>

  76. p>

  77. ##body>

  78. ##html>

  79. notify.php file code, here is a custom method newly added in the official file.





#[php]

view plain

copy


    ##require_once
  1. ROOT_PATH."Api/lib/WxPay.Api.php";

  2. require_once
  3. ROOT_PATH.'Api/lib/WxPay.Notify.php';

  4. require_once
  5. ROOT_PATH.'Api/lib/log.php';

  6. //初始化日志

  7. $logHandler=new\CLogFileHandler(ROOT_PATH."/logs/".date('Y-m-d').'.log');

  8. $log= \Log::Init($logHandler, 15);

  9. classPayNotifyCallBackextendsWxPayNotify

  10. {

  11. protected$para=array('code'=>0,'data'=>'');

  12. //查询订单

  13. publicfunctionQueryorder($transaction_id)

  14. {

  15. $input=new\WxPayOrderQuery();

  16. $input->SetTransaction_id($transaction_id);

  17. $result= \WxPayApi::orderQuery($input);

  18. \Log::DEBUG("query:". json_encode($result));

  19. if(array_key_exists("return_code",$result)

  20. &&array_key_exists("result_code",$result)

  21. &&$result["return_code"] =="SUCCESS"

  22. &&$result["result_code"] =="SUCCESS")

  23. {

  24. returntrue;

  25. }

  26. $this->para['code'] = 0;

  27. $this->para['data'] ='';

  28. ##returnfalse;

  29. }

  30. //Rewrite the callback processing function

  31. ##publicfunctionNotifyProcess($data, &$msg)

  32. {

  33. ##\Log::DEBUG(
  34. " call back:"

    . json_encode($data));

  35. $notfiyOutput

    =array();

  36. if(!array_key_exists("transaction_id",$data)){

  37. $msg="Input parameters are incorrect";

  38. $this->para['code'] = 0;

  39. $this->para['data'] ='';

  40. ##returnfalse;

  41. }

  42. //Query the order to determine if the order is genuine sex

  43. if(!$this->Queryorder($ data["transaction_id"])){

  44. # #$msg="Order query failed";

  45. $this->para['code'] = 0;

  46. $this->para['data'] ='';

  47. #returnfalse;

  48. }

  49. $this->para['code'] = 1;

  50. $this->para['data'] =$data;

  51. returntrue;

  52. }

  53. /**

  54. ## * Custom method to detect whether the callback on WeChat is successful

  55. * @return multitype:number string

  56. */

  57. ##publicfunctionIsSuccess(){

  58. ##return

    $this->para;

    ## }
  59. }
  60. This is basically completed. You can open
http://test.paywechat on WeChat. com/Charge/index.php/Test/index/

Related recommendations:

detailed explanation of nodejs implementation of WeChat payment function example

Thinkphp integrates WeChat payment function

How to add this WeChat payment function to the PC website

The above is the detailed content of PHP implements WeChat payment function development code sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!