PHP implementation WeChat Small program payment code sharing

Source: Internet
Author: User
PHP function is very powerful, this article we mainly share with you the PHP backend implementation of small program payment code, front-end: Relatively simple, in the corresponding payment event on the network request is good:

Small program to pay back-end PHP (ii)

View_moneysure:function () {var code = This.data.code; Console.log (' Code is ' +code ') wx.request ({url: ' https://...com/pay.php ',//This link is back-written header: {' content-t Ype ': ' application/x-www-form-urlencoded '}, data: {Code:code,}, Method: ' POST ', Succe        Ss:function (response) {console.log (response.data);          Initiate payment wx.requestpayment ({' appId ': response.data.appId, ' timeStamp ': Response.data.timeStamp,          ' Noncestr ': response.data.nonceStr, ' package ': response.data.package, ' signtype ': ' MD5 ', ' Paysign ': response.data.paySign, ' success ': function (res) {Wx.showtoast ({title: ')            Payment Success '});          Console.log (RES);      }, ' Fail ': function (res) {Console.log (res)}}); }, Fail:function (res) {Console.log (res)}})},

Back-End Code:

1. pay.php//Backend address for applet request

<?php/** * Created by Phpstorm. * USER:UFO * DATE:17/7/18 * Time: PM 5:31 */require_once (' WxPay.Api.php '); class Wxpay {function index () {/        /Initialize Value object $input = new Wxpayunifiedorder ();        Specification of parameters mentioned in the document: Merchant name-seller category $input->setbody ("Testceshi");        The order number should be passed to the server by the small terminal, generated when the user orders, the value of the demo is a generated timestamp $input->setout_trade_no (Time ().        The cost should be passed to the server by the small terminal, when the user orders to inform the server to deal with the amount, the demo value is 1, that is, 1 cents $input->settotal_fee ("1");        $input->setnotify_url ("https://...com/notify.php");//need to write their own notify.php $input->settrade_type ("JSAPI");        From the small terminal to the backend or backend to obtain, write their own acquired, $input->setopenid (' udhncondjcnkjnjknkcssdcabckn ');        $input->setopenid ($this->getsession ()->openid);        Order is consolidated, and the order is returned, and it is an array $order = Wxpayapi::unifiedorder ($input);        JSON returns to the small terminal header ("Content-type:application/json"); Echo $this-&GT;GETJSapiparameters ($order); The Private Function getjsapiparameters ($UnifiedOrderResult) {//Determines whether the uniform order returns PREPAY_ID if (!array_key_exists (" AppID ", $UnifiedOrderResult) | | !array_key_exists ("prepay_id", $UnifiedOrderResult) | |        $UnifiedOrderResult [' prepay_id '] = = "") {throw new wxpayexception ("parameter Error");        } $jsapi = new Wxpayjsapipay ();        $jsapi->setappid ($UnifiedOrderResult ["AppID"]);        $timeStamp = time ();        $jsapi->settimestamp ("$timeStamp");        $jsapi->setnoncestr (Wxpayapi::getnoncestr ());        $jsapi->setpackage ("prepay_id=". $UnifiedOrderResult [' prepay_id ']);        $jsapi->setsigntype ("MD5");        $jsapi->setpaysign ($jsapi->makesign ());        $parameters = Json_encode ($jsapi->getvalues ());    return $parameters; }//here is the server-side get OpenID function//Private function getsession () {//$code = $this->input->post (' Code ');//$ur L = ' Https://api.weixin.qq.com/sns/jscode2session?appid= '. Wxpayconfig::appid. ' &secret= '. Wxpayconfig::appsecret. ' &js_code= '. $code. ' &grant_type=authorization_code ';//$response = Json_decode (file_get_contents ($url));//return $response; }} $WxPay = new Wxpay (); $WxPay->index ();

2. SDK Download Link: https://pay.weixin.qq.com/wiki/doc/api/download/WxpayAPI_php_v3.zip

Unzip under the Lib folder to see:


To a directory accessible to the server.

Configure the account information in wxpayconfig.php:

Class wxpayconfig{//======= "Basic information Settings" =====================================///** * TODO: Modify the Merchant information configured here for your own application * Public number information configuration *  * APPID: Binding payment of APPID (must be configured, the opening email can be viewed) *  * Mchid: Merchant Number (must be configured, can be viewed in the account opening mail) *  * key: Merchant payment key, refer to account opening mail settings (must be configured, Login to the merchant platform to set your own) * Set address: Https://pay.weixin.qq.com/index.php/account/api_cert *  * Appsecret: Public account Secert (JSAPI only need to be configured when paying, login to the public platform, enter 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 = ' wx123456789 ... ';// Here fill in the corresponding information of the const MCHID = ' 14151666888 '; const KEY = ' 11223344556677889900 '; const Appsecret = ' 828bfsdibfsiubfikdbfik '; Const notify_url= ' https://...com/notify.php ';

Note:

During the encounter a signature error, has been bad, using the Payment Interface Signature Check tool check is not wrong, like the online said the missing write wrong write parameters are checked, is always back

<return_code><! [cdata[fail]]></return_code>
<return_msg><! [cdata[Signature Error]]></return_msg>
This information, the Final solution is: Reset the key (merchant payment key), reset and the same as before, but unexpectedly can ...

The main problem is to report the signature error, carefully check the good, such as the XML format is not correct, MD5 encryption of the number of digits, the dictionary is not sorted well, missing parameters and so on ...

Https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1&index=1

3. Finally attach notify.php

<?php/** * Created by Phpstorm. * USER:UFO * DATE:17/7/13 * Time: PM 6:42 */require_once (' WxPay.Api.php '); require_once (' WxPay.Notify.php '); class Paynot Ifycallback extends wxpaynotify{//Inquiry order Public Function Queryorder ($transaction _id) {$input = new Wxpayor        Derquery ();        $input->settransaction_id ($transaction _id);        $result = Wxpayapi::orderquery ($input); if (array_key_exists ("Return_code", $result) && array_key_exists ("Result_code", $result) &amp            ;& $result ["return_code"] = = "SUCCESS" && $result ["result_code"] = = "SUCCESS") {        return true;    } return false;        }//overriding callback handler public function notifyprocess ($data, & $msg) {$notfiyOutput = array ();            if (!array_key_exists ("transaction_id", $data)) {$msg = "input parameter is incorrect";        return false;         }//Inquiry order, Judge order authenticity if (! $this->queryorder ($data ["transaction_id"]) {   $msg = "Order query failed";        return false;    } return true; }} $notify = new Paynotifycallback (); $notify->handle (false);

Welcome message to communicate correct!

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.