This article mainly introduces the PHP payment development process in detail and has some reference value. interested partners can refer to the PHP payment development process and share it with you for your reference, the details are as follows:
1. development environment
Thinkphp 3.2.3
: Service number, certified
Development domain name: http://test.paywechat.com (custom domain name, Internet inaccessible)
2. related files and permissions are required.
Apply for activation for payment
Public Platform Developer Documentation: http://mp.weixin.qq.com/wiki/home/index.html
Payment developer documentation: https://pay.weixin.qq.com/wiki/doc/api/index.html
Payment SDK: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php? Chapter = 11_1
3. Development
Download the php sdk. the file directory is:
Put the Cert and Lib directories of the payment SDK into Thinkphp. The directory is
This section describes the payment authorization Directory. first, fill in the payment authorization directory in the payment development configuration,
Then fill in the JS interface security domain.
Finally, set webpage authorization
After completing these settings, you will be half done. pay attention to the set directory and the Directory in my thinkphp.
4. payment configuration
Enter the relevant configuration correctly.
/*** Configure account information */class WxPayConfig {// ======== [basic information settings] ========== ========================================/// *** TODO: modify the configuration here to the merchant information you have applied for * public account information configuration ** APPID: bound to the payment APPID (required, which can be viewed in the account opening email) ** MCHID: merchant ID (required, which can be viewed in the account opening email) ** KEY: Merchant's payment KEY. for details, refer to the account opening email settings (required, which can be set by logging on to the merchant platform) * Set the address: https://pay.weixin.qq.com/index.php/account/api_cert ** APPSECRET: secert of the public account (configuration is required only when JSAPI is used for payment. you can set it when logging on to the public platform and entering the Developer Center). * obtain the 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 you should enter the absolute path (only required for refund and order revocation, you can log on to the merchant platform to download it, * API certificate: https://pay.weixin.qq.com/index.php/account/api_cert Install the merchant operation certificate before downloading.) * @ var path */const SSLCERT_PATH = '.. /cert/apiclient_cert.pem '; const SSLKEY_PATH = '.. /cert/apiclient_key.pem '; // ======= [curl proxy settings] ================================ ===========/*** TODO: the proxy machine is set here. it is set only when proxy is required. no proxy is required. set it to 0.0.0.0 and 0 *. this routine uses the http post method through curl. here the proxy server can be modified, * CURL_PROXY_HOST = 0.0.0.0 and CURL_PROXY_PORT = 0 by default. at this time, the proxy is not enabled (if necessary) * @ var unknown_type */const CURL_PROXY_HOST = "0.0.0.0"; // "1 0.152.18.220 "; const CURL_PROXY_PORT = 0; // 8080; // ========= [report information configuration] ================================== ===========/*** TODO: API call reporting level. by default, the error reporting is tight (note: The reporting time is [1 s], no matter whether the report is successful or not [No exception is thrown], * the interface call process is not affected). after reporting is enabled, to facilitate monitoring of the quality of request calls, it is recommended that at least * enable error reporting. * Report level: 0. disable reporting; 1. report errors only; 2. Full report * @ var int */const REPORT_LEVENL = 1 ;}
Now paste the code:
Namespace Wechat \ Controller; use Think \ Controller;/*** parent class Controller, which must inherit * @ file ParentController. class. php * @ author Gary
* @ Date July 15, August 4, 2015 * @ todu */class ParentController extends Controller {protected $ options = array ('token' => '', // enter your set key 'enablingaeskey' => '', // enter the encryption encodingaeskey 'appid '=> '', // enter the app id 'appsecret' => ''of the advanced call function, // enter the key of the advanced call function 'debug' => false, 'logcallback' => ''); public $ errCode = 40001; public $ errMsg =" no access "; /*** get access_token * @ return mixed | boolean | unknown */publ Ic 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) {$ token = $ 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;} public function getFileCache ($ name) {return S ($ name );} /*** the api does not support json structure escaped from Chinese characters * @ 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); $ m Ax_length = count ($ arr)-1; if ($ keys [0] === 0) & ($ keys [$ max_length] ===$ max_length )) {// See if the first key is 0 and last key is length-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 shoshould be in the lookout? (Object ?) $ Parts [] = $ str ;}$ json = implode (',', $ parts); if ($ is_list) return '['. $ json. ']'; // Return numerical JSON return '{'. $ json. '}'; // Return associative JSON}/** + random * Generate random string + ------------------------------------------------------------ * @ param int $ length: 0, numbers + uppercase/lowercase letters; 1, numbers; 2, lowercase letters; 3, uppercase letters; 4, Special characters;-1, numbers + uppercase/lowercase letters + Special Characters + ------------------------------------------------------ * @ return string + functions */static public 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 (stri Pos ($ url, "https ://")! = FALSE) {curl_setopt ($ oCurl, success, 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) {retu Rn $ sContent;} else {return false ;}} /*** POST request * @ param string $ url * @ param array $ param * @ param boolean $ post_file whether to upload files * @ return string content */private function http_post ($ url, $ param, $ post_file = false) {$ oCurl = curl_init (); if (stripos ($ url, "https ://")! = FALSE) {curl_setopt ($ oCurl, success, 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;/*** payment test Controller * @ file TestController. class. php * @ author Gary
* @ Date March 13, August 4, 2015 * @ todu */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 () {// ①. obtain the user openid $ tools = new \ JsApiPay (); $ openId = $ tools-> GetOpenid (); // ② unified order $ input = new \ WxPayUnifiedOrder (); // product description $ input-> SetBody ($ this-> _ order_body); // additional data, you can add the data you need. this data will be appended when the callback is asynchronous. $ input-> SetAttach ('XXX'); // merchant order number $ out_trade_no = \ WxPayConfig: MCHID. date ("YmdHis"); $ input-> SetOut_trade_no ($ out_trade_no); // total amount, total order amount, which can only be an integer, in the unit of $ input-> settotal_hour (1 ); // transaction start time $ input-> SetTime_start (date ("YmdHis"); // transaction end time $ input-> SetTime_expire (date ("YmdHis", time () + 600); // The product tag $ input-> SetGoods_tag ($ this-> _ order_goods_tag); // The notification address. the callback address SITE_URL = http://test.paywechat.com/Charge $ Yy_url = SITE_URL. '/index. php/Test/yy.html '; $ input-> setpolicy_url ($ policy_url); // transaction type $ input-> SetTrade_type ("JSAPI "); $ input-> SetOpenid ($ openId); $ order = \ WxPayApi: unifiedOrder ($ input); $ jsApiParameters = $ tools-> GetJsApiParameters ($ order ); // Get the shared shipping address. js function parameter $ editAddress = $ tools-> GetEditAddressParameters (); $ this-> assign ('openid', $ openId ); $ this-> assign ('jsapiparameters ', $ jsApiParamete Rs); $ this-> assign ('editaddress', $ editAddress); $ this-> display ();} /*** asynchronous notification callback method */public function callback Y () {require_once ROOT_PATH. "Api/lib/notify. php "; $ policy = new \ paypolicycallback (); $ policy-> Handle (false); // Here, IsSuccess is a custom method, I will post the code for this file for your reference. $ Is_success = $ policy-> IsSuccess (); $ bdata = $ is_success ['data']; // if the payment is successful ($ is_success ['code'] = 1) {$ news = array ('touser' => $ bdata ['openid'], 'msgtype' => 'news ', 'news' => array ('articles' => array ('title' => 'Order payment successful ', 'description' => "payment amount: {$ bdata ['total _ timeout']} \ n ". "Order No.: {$ bdata ['transaction _ id']} \ n" 'picurl' => '', 'URL' => '')))); // send a payment notification $ this-> sendCustomMessage ($ news );} else {// payment failed}/** payment success Page * unreliable callback */public function ajax_PaySuccess () {// Order No. $ out_trade_no = I ('post. out_trade_no '); // payment amount $ total_amount = I ('post. total_fee ');/* related logic processing */}
Paste template HTML
Payment example-payment