PHP WeChat payment demo

Source: Internet
Author: User
Tags openid
This article mainly introduces the relevant information of PHP payment demo. if you need it, you can refer to all the information in the code. the code contains comments. thank you for your reference.

<? Phpclass WxpayService {protected $ mchid; protected $ appid; protected $ key; public function _ construct ($ mchid, $ appid, $ key) {$ this-> mchid = $ mchid; // the payment merchant ID is sent by email after the payment merchant information is reviewed $ this-> appid = $ appid; // the public account APPID is sent by email $ this-> key = $ key after being reviewed by the payment merchant ;// https://pay.weixin.qq.com Account Settings-security settings-API security-API key-set API key}/*** @ param string $ openid call the [webpage authorization to obtain user information] interface to obtain the user information in this public openid * @ param float $ totalFee total charge unit * @ param string $ unique Order Number of outTradeNo * @ param string $ orderName order name * @ param string $ policyurl payment result do not have question marks for the notification url * https://mp.weixin.qq.com/ Payment-development configuration-test directory * Test Directory http://mp.izhanlue.com/paytest/ The last Slash is required (the directory must be accurate to level 2 or level 3) * @ return string */public function createJsBizPackage ($ openid, $ totalpackages, $ outTradeNo, $ orderName, $ policyurl, $ timestamp) {$ config = array ('mch _ id' => $ this-> mchid, 'appid '=> $ this-> appid, 'key' => $ this-> key,); $ uniied = array ('appid '=> $ config ['appid'], 'Attach '=> 'pay ', // merchant data packet, returns 'body' =>$ orderName, 'mch _ id' =>$ config ['mch _ id'], 'nonce _ str' => self: createNonceStr (), 'Your y _ url' => $ notifyUrl, 'openid' => $ openid, // rade_type = JSAPI, this parameter must be set to 'out _ trade_no '=> $ outTradeNo, 'spbill _ create_ip' => '127. 0.0.1 ', 'total _ upload' => intval ($ totalval * 100), // The unit is converted to 'trade _ type' => 'japi ',); $ uniied ['sign'] = self: getSign ($ uniied, $ config ['key']); $ responseXml = self: curlPost (' https://api.mch.weixin.qq.com/pay/unifiedorder ', Self: arrayToXml ($ uniied ));/*
     
  SUCCESS
      
  OK
      wx00e5904efec77699    
  1220647301
      
  1LHBROsdmqfXoWQR
      
  ACA7BC8A9164D1FBED06C7DFC13EC839
      
  SUCCESS
      
  wx2015032016590503f1bcd9c30421762652
      
  JSAPI
      
 */$ UnifiedOrder = simplexml_load_string ($ responseXml, 'simplexmlelement', LIBXML_NOCDATA); if ($ unifiedOrder = false) {die ('parse xml error ');} if ($ unifiedOrder-> return_code! = 'Success') {die ($ unigiedorder-> return_msg);} if ($ unigiedorder-> result_code! = 'Success') {die ($ unifiedOrder-> err_code ); /* The NOAUTH merchant does not have this interface permission. the NOTENOUGH balance is insufficient. the ORDERPAID merchant order has been paid. the ORDERCLOSED order has been closed. SYSTEMERROR: APPID_NOT_EXIST. APPID does not exist. the parameter paiappid and mch_id do not match duplicate order number SIGNERROR signature error XML_FORMAT_ERROR XML format error REQUIRE_POST_METHOD please use post method POST_DATA_EMPTY post data is empty NOT_UTF8 encoding format error */} // $ unifiedOrder-> trade_type transaction type call interface submitted transaction type, the values are as follows: JSAPI, NATIVE, APP // $ unifiedOrder-> prepay_id: the pre-payment session id generated by the pre-payment session ID, used in subsequent interface calls, this value is valid for 2 hours // $ unifiedOrder-> code_url QR code link trade_type is returned for NATIVE, you can generate a QR code for this parameter value and pay by scanning the QR code $ arr = array ("appId" => $ config ['appid '], "timeStamp" => $ timestamp, "nonceStr" => self: createNonceStr (), "package" => "prepay_id = ". $ unifiedOrder-> prepay_id, "signType" => 'md5',); $ arr ['paysign'] = self: getSign ($ arr, $ config ['key']); return $ arr;} public function using Y () {$ config = array ('mch _ id' => $ this-> mchid, 'appid '=> $ this-> appid, 'key' => $ this-> key,); $ postStr = $ GLOBALS ["HTTP_RAW_POST_DATA"]; // error_log ($ postStr, 3 ,'. /str.txt ');/* $ postStr ='
     wx00e5904efec77699    支付测试    
  CMB_CREDIT
      
  1
      
  CNY
      
  Y
      
  1220647301
      
  a0tZ41phiHm8zfmO
      
  oU3OCt5O46PumN7IE87WcoYZY9r0
      
  550bf2990c51f
      
  SUCCESS
      
  SUCCESS
      
  F6F519B4DD8DB978040F8C866C1E6250
      
  20150320181606
      
  
   
1
      
  JSAPI
      
  1008840847201503200034663980
      
 '; */$ PostObj = simplexml_load_string ($ postStr, 'simplexmlelement', LIBXML_NOCDATA); if ($ postObj = false) {die ('parse xml error ');} if ($ postObj-> return_code! = 'Success') {die ($ postObj-> return_msg);} if ($ postObj-> result_code! = 'Success') {die ($ postObj-> err_code);} $ arr = (array) $ postObj; unset ($ arr ['sign']); if (self:: getSign ($ arr, $ config ['key']) ==$ postObj-> sign) {// $ mch_id = $ postObj-> mch_id; // payment for the assigned merchant ID // $ appid = $ postObj-> appid; // The assigned public account ID // $ openid = $ postObj-> openid; // the unique ID of the user under the Merchant appid // $ transaction_id = $ postObj-> transaction_id; // Payment Order No. // $ out_trade_no = $ postObj-> out_trade_no; // merchant Order No. // $ total_amount = $ postObj-> total_amount; // total order amount, in the unit of minute/$ is_subscribe = $ postObj-> is_subscribe; // whether the user pays attention to the public account, Y-follow, N-not follow, only valid for payment under the public account type // $ attach = $ postObj-> attach; // merchant data packets, returns the original response // $ time_end = $ postObj-> time_end; // The payment completion time echo'
 
  SUCCESS
  
  OK
  
 '; Return $ postObj ;}} /*** curl get *** @ param string $ url * @ param array $ options * @ return mixed */public static function curlGet ($ url = '', $ options = array () {$ ch = curl_init ($ url); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ ch, CURLOPT_TIMEOUT, 30); if (! Empty ($ options) {curl_setopt_array ($ ch, $ options);} // https requests do not verify the certificate and host curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, false ); curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, false); $ data = curl_exec ($ ch); curl_close ($ ch); return $ data ;} public static function curlPost ($ url = '', $ postData ='', $ options = array () {if (is_array ($ postData )) {$ postData = http_build_query ($ postData);} $ ch = curl_init (); Curl_setopt ($ ch, CURLOPT_URL, $ url); curl_setopt ($ ch, batch, 1); curl_setopt ($ ch, CURLOPT_POST, 1); curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ postData); curl_setopt ($ ch, CURLOPT_TIMEOUT, 30); // sets the maximum number of seconds that cURL can be executed if (! Empty ($ options) {curl_setopt_array ($ ch, $ options);} // https requests do not verify the certificate and host curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, false ); curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, false); $ data = curl_exec ($ ch); curl_close ($ ch); return $ data;} public static function createNonceStr ($ length = 16) {$ chars = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 '; $ str = ''; for ($ I = 0; $ I <$ length; $ I ++) {$. str. = substr ($ chars, mt_rand (0, strlen ($ chars)-1), 1) ;}return $ str ;} public static function arrayToXml ($ arr) {$ xml ="
 
  
"; Foreach ($ arr as $ key => $ val) {if (is_numeric ($ val) {$ xml. = "<". $ key. "> ". $ val."
  ";} Else $ xml. =" <". $ key.">" . $val . "
  ";}$ Xml. ="
 "; Return $ xml;}/*** example: * appid: wxd930ea5d5a258f4f * mch_id: 10000100 * device_info: 1000 * Body: test * nonce_str: ibuaiVcKdpRxkhJA * Step 1: the parameters are in key = value format and sorted in the ASCII lexicographic order of parameter names as follows: * stringA = "appid = wxd930ea5d5a258f4f & body = test & device_info = 1000 & mch_ I * d = 10000100 & nonce_str = ibuaiVcKdpRxkhJA"; * Step 2: splice the payment key: * stringSignTemp = "stringA & key = 192006250b4c09247ec02edce69f6a2d" * sign = MD5 (stringSignTemp). ToUpperCase () = "callback" */public static function getSign ($ params, $ key) {ksort ($ params, SORT_STRING); $ unSignParaString = self: formatQueryParaMap ($ params, false); $ signStr = strtoupper (md5 ($ unSignParaString. "& key = ". $ key); return $ signStr;} protected static function formatQueryParaMap ($ paraMap, $ urlEncode = false) {$ buff = ""; ksort ($ paraMap ); foreach ($ paraMap S $ k => $ v) {if (null! = $ V & "null "! = $ V) {if ($ urlEncode) {$ v = urlencode ($ v);} $ buff. = $ k. "= ". $ v. "&" ;}}$ reqPar = ''; if (strlen ($ buff)> 0) {$ reqPar = substr ($ buff, 0, strlen ($ buff) -1);} return $ reqPar ;}}

You can understand the above code. if you don't understand anything, please leave a message. I will contact you immediately. Thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.