PHP Micro-credit payment development process, to share with you for your reference, the specific content as follows
1. Development environment
thinkphp 3.2.3
Micro-letter: Service number, certified
Development Domain Name: http://test.paywechat.com (custom domain name, extranet inaccessible)
2. Need relevant documents and authority
Micro-letter payment to be opened for application
Micro-trust public Platform Developer Documentation: http://mp.weixin.qq.com/wiki/home/index.html
Micro-credit Payment developer Documentation: https://pay.weixin.qq.com/wiki/doc/api/index.html
Micro-credit Payment SDK download address: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1
3. Development
Download the micro-letter payment PHP version of the SDK, file directory for the following figure:
Put the Cert and Lib directory of the micro-credit payment SDK into the thinkphp directory
Now introduce the issue of micro-letter Payment Authorization directory, the first is the micro-credit payment development configuration inside the payment authorization directory to fill out,
Then fill in the JS interface security domain.
Finally set up the page authorization
These settings are finished, basically half done, note the set directory and my thinkphp inside the directory.
4. Micro-Credit Payment configuration
Fill in the relevant configuration correctly.
/** * Configuration Account information */class Wxpayconfig {//======= "Basic information Settings" =====================================///** * TODO: Modify here to configure for yourself Application for merchant information * Micro-trust Information configuration * * APPID: Binding payment APPID (must be configured, open account Mail can be viewed) * * Mchid: Merchant Number (must be configured, account open Mail can be viewed) * Key: Merchant payment key, refer to account opening mail settings (must be matched with Set, login merchant platform set up by itself) * Address: Https://pay.weixin.qq.com/index.php/account/api_cert * * Appsecret: Public account Secert (only JSAPI payment needs to be configured, Login to the public platform, access to the developer Center can be set up), * get address: https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=
2005451881&LANG=ZH_CN * @var string/Const APPID = ';
Const MCHID = ';
Const KEY = ';
Const Appsecret = ';
======= "Certificate path Settings" =====================================/** * TODO: Set the Merchant certificate path * Certificate path, note that the absolute path should be filled in (refund only, cancel order required, can login to the merchant platform download, * API certificate Download address: Https://pay.weixin.qq.com/index.php/account/api_cert, before downloading need to install merchant operation Certificate * @var path/Const Sslcert_path = '.
./cert/apiclient_cert.pem '; Const Sslkey_path = '..
/cert/apiclient_key.pem '; ======= "Curl proxy settings" ===================================/** * TODO: Here set up the agent machine, onlyWhen there is a need for agents to set up, do not need agents, please set to 0.0.0.0 and 0 * This routine uses the HTTP POST method through curl, where you can modify the proxy server, * default curl_proxy_host=0.0.0.0 and curl_proxy_port=
0, at this time do not open the agent (if necessary to set up) * @var unknown_type/Const CURL_PROXY_HOST = "0.0.0.0";/"10.152.18.220";
Const CURL_PROXY_PORT = 0;//8080; ======= "Escalation information Configuration" ===================================/** * TODO: Interface call escalation level, default tight error escalation (note: escalation time is "1s", reported regardless of success or failure "never throw an exception", *
Does not affect the interface invoke process), after the escalation, to facilitate the micro-credit monitoring request call quality, recommended at least * open error escalation. * Escalation level, 0. Close the report; 1. Error reporting only;
2. Full report * @var int */CONST REPORT_LEVENL = 1;
}
Start posting the code now:
namespace Wechat\controller;
Use Think\controller; /** * Parent class controller, need to inherit * @file ParentController.class.php * @author Gary <lizhiyong2204@sina.com> * @date August 4, 2015 * @todu */class Parentcontroller extends Controller {protected $options = Array (' token ' => ',//fill in your Set key ' en Codingaeskey ' => ',//fill in encrypted Encodingaeskey ' AppID ' => ',//fill in the Advanced Call Feature app ID ' appsecret ' => ',//fill in the advanced Call feature's Secret
Key ' Debug ' => false, ' logcallback ' => ');
Public $errCode = 40001;
Public $ERRMSG = "No access"; /** * Get Access_token * @return Mixed|boolean|unknown/Public Function GetToken () {$cache _token = S (' Exp_wechat_pay_
Token ');
if (!empty ($cache _token)) {return $cache _token;
} $url = ' https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s ';
$url = sprintf ($url, $this->options[' AppID '), $this->options[' Appsecret ']);
$result = $this->http_get ($url);
$result = Json_decode ($result, true); if (empty ($result)) {
return false;
} S (' Exp_wechat_pay_token ', $result [' Access_token '],array (' type ' => ' file ', ' expire ' =>3600));
return $result [' Access_token '];
/** * Send customer service message * @param array $data message structure {"Touser": "OPENID", "Msgtype": "News", "news": {...}}
* * Public Function Sendcustommessage ($data) {$token = $this->gettoken ();
if (empty ($token)) return false;
$url = ' https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s ';
$url = sprintf ($url, $token);
$result = $this->http_post ($url, Self::json_encode ($data));
if ($result) {$json = Json_decode ($result, true);
if (! $json | | |!empty ($json [' Errcode '])) {$this->errcode = $json [' Errcode '];
$this->errmsg = $json [' errmsg '];
return false;
return $json;
return false; /** * Send Template message * @param unknown $data * @return Boolean|unknown/Public Function sendtemplatemessage ($data) {$to
Ken = $this->gettoken ();
if (empty ($token)) return false; $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s ";
$url = sprintf ($url, $token);
$result = $this->http_post ($url, Self::json_encode ($data));
if ($result) {$json = Json_decode ($result, true);
if (! $json | | |!empty ($json [' Errcode '])) {$this->errcode = $json [' Errcode '];
$this->errmsg = $json [' errmsg '];
return false;
return $json;
return false;
The Public Function Getfilecache ($name) {return S ($name);
The/** * Micro-trust API does not support the Chinese escaped JSON structure * @param array $arr/static function Json_encode ($arr) {$parts = array ();
$is _list = false;
Find out if the given array is a numerical array $keys = Array_keys ($arr);
$max _length = count ($arr)-1; if ($keys [0] = 0) && ($keys [$max _length] = = $max _length)) {//see if the
Gth-1 $is _list = true; for ($i = 0; $i < count ($keys); $i + +) {//see If each key correspondes to its position if ($i!= $keys [$i]) {//a
Key fails at position check. $is _list = false;
It is an associative array. Break
foreach ($arr as $key => $value) {if (Is_array ($value)) {//custom Handling for arrays if ($is _list) $parts [] = Self::json_encode ($value); /*: recursion: * Else $parts [] = ' ". $key. '":' . Self::json_encode ($value);
/*: recursion:/else {$str = '; if (! $is _list) $str = ' "'. $key.
'":'; Custom handling for multiple data types if (!is_string ($value) && is_numeric ($value) && $value 2000000000) $str. = $value; Numbers ElseIf ($value = = False) $str. = ' false ';
The Booleans elseif ($value = = True) $str. = ' true '; else $str. = ' "'. Addslashes ($value). '"'; All other things//: Todo:is There any more datatype we should is in the lookout for?
(Object?)
$parts [] = $STR;
}} $json = Implode (', ', $parts); if ($is _list) return ' ['. $json. ']'; Return numerical JSON return ' {'. $json. '}'; return associative JSON}/** +----------------------------------------------------------* Generate a random string +----------------------------------------------------------* @param int $length The length of the random string to be generated * @param string $type Random code type: 0, numbers + uppercase and lowercase letters 1, digits, 2, lower-case letters 3, uppercase; 4, special characters;-1, number + uppercase + special characters +--------------------------------- -------------------------* @return string +----------------------------------------------------------/Static Publ IC function Randcode ($length = 5, $type = 2) {$arr = array (1 => "0123456789", 2 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 3
=> "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&* () {}[]|");
if ($type = = 0) {array_pop ($arr);
$string = Implode ("", $arr);
} elseif ($type = = "1") {$string = Implode ("", $arr);
else {$string = $arr [$type];
$count = strlen ($string)-1;
$code = ';
for ($i = 0; $i < $length; $i + +) {$code. = $string [rand (0, $count)];
return $code;
/** * GET request * @param string $url/Private Function Http_get ($url) {$oCurl = Curl_init (); if (Stripos ($url, "https://")!==false) {Curl_setOpt ($oCurl, Curlopt_ssl_verifypeer, FALSE);
curl_setopt ($oCurl, Curlopt_ssl_verifyhost, FALSE); curl_setopt ($oCurl, curlopt_sslversion, 1);
CURL_SSLVERSION_TLSV1} curl_setopt ($oCurl, Curlopt_url, $url);
curl_setopt ($oCurl, Curlopt_returntransfer, 1);
$sContent = curl_exec ($oCurl);
$aStatus = Curl_getinfo ($oCurl);
Curl_close ($oCurl);
if (Intval ($aStatus ["Http_code"]) ==200) {return $sContent;
}else{return false; /** * POST Request * @param string $url * @param array $param * @param boolean $post _file whether file upload * @return string C
Ontent */Private Function Http_post ($url, $param, $post _file=false) {$oCurl = Curl_init ();
if (Stripos ($url, "https://")!==false) {curl_setopt ($oCurl, Curlopt_ssl_verifypeer, FALSE);
curl_setopt ($oCurl, Curlopt_ssl_verifyhost, false); curl_setopt ($oCurl, curlopt_sslversion, 1);
CURL_SSLVERSION_TLSV1} if (is_string ($param) | | | $post _file) {$strPOST = $param;
else {$aPOST = array (); foreach ($param as $key => $val) {$aPOST [] = $Key. "
= ". UrlEncode ($val);
} $strPOST = Join ("&", $aPOST);
curl_setopt ($oCurl, Curlopt_url, $url);
curl_setopt ($oCurl, Curlopt_returntransfer, 1);
curl_setopt ($oCurl, curlopt_post,true);
curl_setopt ($oCurl, Curlopt_postfields, $strPOST);
$sContent = curl_exec ($oCurl);
$aStatus = Curl_getinfo ($oCurl);
Curl_close ($oCurl);
if (Intval ($aStatus ["Http_code"]) ==200) {return $sContent;
}else{return false;
}
}
}
namespace Wechat\controller;
Use Wechat\controller\parentcontroller; /** * Micro-Credit Payment test controller * @file TestController.class.php * @author Gary <lizhiyong2204@sina.com> * @date August 4, 2015 * @t
ODU * * Class TestController extends Parentcontroller {private $_order_body = ' xxx ';
Private $_order_goods_tag = ' xxx ';
Public Function __construct () {parent::__construct (); Require_once Root_path. "
Api/lib/wxpay.api.php "; Require_once Root_path. "
Api/lib/wxpay.jsapipay.php ";
Public Function Index () {//①, get user OpenID $tools = new \jsapipay ();
$openId = $tools->getopenid ();
②, unified under single $input = new \wxpayunifiedorder ();
Product Description $input->setbody ($this->_order_body);
Additional data, you can add the data you need, micro-mail back to the asynchronous callback will append this data $input->setattach (' xxx ');
Merchant Order number $out _trade_no = \wxpayconfig::mchid.date ("Ymdhis");
$input->setout_trade_no ($out _trade_no);
Total amount, order total amount, can only be integer, the unit is divided into $input->settotal_fee (1);
Transaction Start date $input->settime_start ("Ymdhis"); Transaction End time $input->settime_expire (daTe ("Ymdhis", Time () + 600));
Commodity marking $input->setgoods_tag ($this->_order_goods_tag); Notification address, receiving a micro-letter payment asynchronous notification callback address Site_url=http://test.paywechat.com/charge $notify _url = site_url. '
/index.php/test/notify.html ';
$input->setnotify_url ($notify _url);
Transaction type $input->settrade_type ("Jsapi");
$input->setopenid ($openId);
$order = \wxpayapi::unifiedorder ($input);
$jsApiParameters = $tools->getjsapiparameters ($order);
Get Shared receipt address js function parameter $editAddress = $tools->geteditaddressparameters ();
$this->assign (' openId ', $openId);
$this->assign (' jsapiparameters ', $jsApiParameters);
$this->assign (' editaddress ', $editAddress);
$this->display (); /** * Asynchronous Notification callback method/Public function notify () {require_once root_path. "
Api/lib/notify.php ";
$notify = new \paynotifycallback ();
$notify->handle (FALSE);
The issuccess here is a method of my customization, and I will post the code of this file for reference.
$is _success = $notify->issuccess ();
$bdata = $is _success[' data ']; Payment success if ($is _success[' code '] = = 1) {$news = array(' Touser ' => $bdata [' OpenID '], ' msgtype ' => ' news ', ' News ' => Array (' articles ' => array (
' title ' => ' Order payment success ', ' description ' => ' Payment amount: {$bdata [' total_fee ']}\n '].
"Micro-Letter order number: {$bdata [' transaction_id ']}\n" ' picurl ' => ', ' url ' => ')));
Send micro-letter payment Notice $this->sendcustommessage ($news); }else{//Payment Failure}/** * Payment success Page * Unreliable callback/Public function ajax_paysuccess () {//order number $out _trade_no = I (' Post.out_
Trade_no ');
Payment amount $total _fee = I (' Post.total_fee ');
/* Related logic processing */}
Paste Template HTML
notify.php file code, here is a new custom method added in the official file.
Require_once Root_path. "
Api/lib/wxpay.api.php ";
Require_once root_path. ' api/lib/wxpay.notify.php ';
Require_once root_path. ' api/lib/log.php '; Initialize log $logHandler = new \clogfilehandler (Root_path.) /logs/". Date (' y-m-d ').
Log ");
$log = \log::init ($logHandler, 15);
Class Paynotifycallback extends Wxpaynotify {protected $para = array (' Code ' =>0, ' data ' => ');
Query order Public Function Queryorder ($transaction _id) {$input = new \wxpayorderquery ();
$input->settransaction_id ($transaction _id);
$result = \wxpayapi::orderquery ($input); \log::D ebug ("Query:").
Json_encode ($result)); if (array_key_exists ("Return_code", $result) && array_key_exists ("Result_code", $result) && $result ["
Return_code "] = =" SUCCESS "&& $result [" result_code "] = =" SUCCESS ") {return true;
} $this->para[' code ' = 0;
$this->para[' data '] = ';
return false; //Overrides the callback handler function, Public function notifyprocess ($data, & $msg) {\log::D ebug (called back:).
Json_encode ($data)); $nOtfiyoutput = Array ();
if (!array_key_exists ("transaction_id", $data)) {$msg = "Incorrect input parameters";
$this->para[' code '] = 0;
$this->para[' data '] = ';
return false;
//Enquiry Order, Judge order authenticity if (! $this->queryorder ($data ["transaction_id"])) {$msg = "order query failed";
$this->para[' code '] = 0;
$this->para[' data '] = ';
return false;
} $this->para[' code ' = 1;
$this->para[' data '] = $data;
return true; /** * Custom method detects whether the micro-end callback succeeds method * @return Multitype:number string/Public function issuccess () {return $this->para
;
}
}
Basically done here, you can open the http://test.paywechat.com/Charge/index.php/Test/index/at the micro-letter end
my environment, HTTP server did not rewrite the URL, micro-letter payment continue to explore, some places may write problems or deficiencies, hope everyone understanding, learn from each other.
The above is the whole content of the PHP micro-credit payment development, I hope to help you learn, but also hope that we support the cloud habitat community.