Micro-Credit Payments finally succeeded (Android, IOS) to share the _android

Source: Internet
Author: User
Tags curl http post openid

After a few days of pain, and finally the micro-letter payment, the whole debugging process is very painful, the main source of pain is the micro-letter payment debugging is really, the previous debugging public number payment is also twists AH. All right, let's go! First of all, I do not use the Gettoken,getorder method here, all of my parameters are generated in the backend to pass to the front end, look at the source code shared by the previous friends, but also used Jquery,md5,sha for beginners is simply astronomical ah, and jquery in the apicloud inefficient, so give up the research that code, in addition, the official said, the best signature and other parameters of all server-side generation, the micro-letter is also said.

Note: the micro-letter itself in the Apicloud config.xml file you need to fix it first.


Take a look at the app-side code first.

function Wx_pay () {Api.ajax ({url:serverurl+ "weixin/example/app.php", Method: ' POST ',
            Timeout: ' DataType: ' json ', Returnall:false, cache:true, data: { Values:{type: "Login"}}, function (ret, err) {if (ret) {var ba
            Ck_info=ret;
            var Weixin = api.require (' Weixin ');
                Weixin.registerapp (function (ret,err) {if (ret.status)
                {Weixin.payorder ({OrderId:back_info.prepayid, PartnerId:back_info.partnerid, NonceStr:back_info.noncestr, TimeStamp:back_info.time Stamp, Package:back_info.package, Sign:back_info.sign},function (ret,e 
               RR) {if (ret.status)    {$alert (' pay success ');
                   else {$alert (err.msg);
                }
                });
                else {$alert (err.msg);
        }
              }
            );
        else {$alert (JSON2STR (err));
}
    });
 }

Completely according to Apicloud write, no problem, we can copy the past use directly, which $alert is my own encapsulation method, is the pop-up information just
The following is mainly the service side, see attachment, download

This is from the micro-letter official download down, Pit Dad's micro-letter to the case is too rubbish, the description is not meticulous, unified under the single interface generated, but the creation of the app data is not, only JS generation, can only write their own, where the signature, random strings, there are time stamps, and so on, each request, production must be again, The more abominable thing is that the case is not consistent, I thought that the direct JS slightly modified to modify the good, the result is not, dead or dead can not find the reason, and then carefully compared with the document looked, JS adjusted to pay a lot of parameters are case, but the app is all lowercase, the specific documents see below:

    • Js:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7
    • App:https://pay.weixin.qq.com/wiki/d ... hapter=9_12&index=2

You can also carefully contrast, do not complain, look at the code.
First Open example/app.php, this is the interface file I wrote

<?php ini_set (' Date.timezone ', ' Asia/shanghai ');
Error_reporting (E_error); Require_once ".
/lib/wxpay.api.php ";
Require_once "WxPay.AppPay.php";
$notify = new Apppay ();
/* First generate prepayid*/$input = new Wxpayunifiedorder (); $input->setbody ("test1");//A brief description of the goods or payment form (must be filled in)//$input->setattach ("test2");//Append data, returned as is in the query API and payment notification, This field is used primarily for custom data that the merchant carries the order (no need to fill in)//$input->setdetail ("Ipad mini 16G White, Black");//List of commodity names (not required) $input->setout_trade_no ( Wxpayconfig::mchid.date ("Ymdhis"))//order number (must be filled) $input->settotal_fee ("1");//Order Amount (must be filled in)//$input->settime_ Start (Date ("Ymdhis"))//Transaction start time (not required)//$input->settime_expire (Date ("Ymdhis", Time () +600))//transaction End times 10 minutes not required) $ Input->setgoods_tag ("test");//mark of goods (not required) $input->setnotify_url ("http://tc.weixinxa.com/app/weixin/example/ . php ");/callback URL (must be filled in) $input->settrade_type (" APP ");//transaction type (must fill in)//$input->setproduct_id (" 123456789 "); Rade_type=native, this parameter must be passed.
This ID is the product ID contained in the two-dimensional code and is defined by the merchant. $order = Wxpayapi::unifiedorder ($input);//Get basic information about the order, including Prepayid $appApiparameters = $notify->getappapiparameters ($order);//Generate some parameters submitted to the app Die ($appApiParameters);?>
 

The above callback URL must be written well, I do not have to do callback in this attachment processing, there will be updates.

Note Some points:
1. The type of transaction must be app, if you are applying for the micro-credit public number payment, not from the https://open.weixin.qq.com/here, it will not be used
2. The first step is to generate order, return an array, to ensure that the array has prepay_id, if not, then you have to check the configuration file lib/wxpay.config.php

Keep looking at the code.
example/wxpay.apppay.php

<?php/** * App Payment Implementation class * @author Widyhu * */class Apppay {/** * * parameter array to URL parameter * @param a
        Rray $URLOBJ */Private Function Tourlparams ($URLOBJ) {$buff = ""; foreach ($urlObj as $k => $v) {$buff. = $k. "=" . $v.
        "&";
        $buff = Trim ($buff, "&");
    return $buff; /** * * Generates a direct payment URL, the payment URL is valid for 2 hours, Mode II * @param unifiedorderinput $input/Public functio n Getpayprepayid ($input) {if ($input->gettrade_type () = = "APP") {$result = Wxpayapi::uni
            Fiedorder ($input);
        return $result; Generate app submission Data/* Public Function Getappapiparameters ($UnifiedOrderResult) {if!array_key_exists ( "AppID", $UnifiedOrderResult) | | !array_key_exists ("prepay_id", $UnifiedOrderResult) | | $UnifiedOrderResult [' prepay_id '] = = "") {throw new WxpayexceptiOn ("parameter error");
        } $appapi = new Wxpayappapipay ();
        $appapi->setappid ($UnifiedOrderResult ["AppID"]);
        $appapi->setpartnerid ($UnifiedOrderResult ["mch_id"]);
        $appapi->setprepayid ($UnifiedOrderResult ["prepay_id"]);
        $timeStamp = time ();
        $appapi->settimestamp ($timeStamp);
        $appapi->setnoncestr (Wxpayapi::getnoncestr ());
        $appapi->setpackage ("Sign=wxpay");
        $appapi->setsign ($appapi->makesign ());
        $back _arr= $appapi->getvalues ();
        $back _arr[' prepay_id ']= $UnifiedOrderResult ["prepay_id"];
        $parameters = Json_encode ($appapi->getvalues ());
    return $parameters;
 }
}

This file is not officially provided, I wrote it myself, modeled after WxPay.NativePay.php this file, mainly to see 42 lines getappapiparameters this function. This generated many of the basic data submitted by the app, in which a class Wxpayappapipay is referenced, the last function in lib/wxpay.data.php, now let's take a look at the configuration file/lib/wxpay.config.php

<?php/** * Configuration Account information */class Wxpayconfig {//======= "Basic information Settings" =====================================// /** * TODO: Modify here to configure your own application for merchant information * Micro-public number information configuration * * APPID: Binding paid APPID (must be configured, open account email can be viewed) * * Mchid: Merchant (Must be configured, account open Mail can be viewed) * Key: Merchant payment key, refer to account opening mail settings (must be configured, login merchant platform set up) * Address: Https://pay.weixin.qq.com/index.php/accou Nt/api_cert * * Appsecret: Public account Secert (only when you need to configure, login to the public platform, access the developer Center can set up), * get address: https://mp.weixin.qq.com/ ADVANCED/ADVANCED?ACTION=DEV&AMP;T=ADVANCED/DEV&AMP;TOKEN=2005451881&AMP;LANG=ZH_CN * @var string/const A
    PPID = ' wxd3ae8cc5ab312345 ';
    Const MCHID = ' 1250189001 ';
    Const KEY = ' 14e1b600b1fd579f47433b88e8d85111 ';
    
    
    Const Appsecret = ' e43930e9e262176356adbf1101e11111 ';
    /* Public number (if you apply for the micro-letter public number to pay instead of micro-letter payment on this, but this is not a way to use in the app, only by scanning code or JS) const APPID = ' WX223C1E5D831C94A5 ';
    Const MCHID = ' 1232570702 ';
    Const KEY = ' 14e1b600b1fd579f47433b88e8d85291 '; Const APPSECRET =' 8d6329ec3fb4195f857aee0749c3aad2 '; * *//======= "certificate path Settings" =====================================/** * TODO: Set the Merchant Certificate path * Certificate path, note should fill in the absolute path (only refund, the need to cancel the order, you can login to the merchant platform download, * API certificate download Address: Https://pay.weixin.qq.com/index.php/account/api_ce RT, 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, only when the agent needs to set up, do not need agents, please set to 0.0.0.0 and 0 * This routine uses the HTTP POST method via curl, where you can modify the proxy server, * default curl_proxy_host=0.0.0.0 and curl_proxy_port=0, do not open the proxy at this time (if necessary) * @var Unkno
    Wn_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 reporting. * Escalation level, 0. Close the report; 1. Error reporting only; 2. Full report * @var INT */Const REPORT_LEVENL = 1;
 }

is mainly modified

    • Const APPID = ' wxd3ae8cc5ab312345 ';
    • Const MCHID = ' 1250189001 ';
    • Const KEY = ' 14e1b600b1fd579f47433b88e8d85111 ';
    • Const Appsecret = ' e43930e9e262176356adbf1101e11111 ';

The rest of you don't move.
So much, I'm going to write back the URL of the callback process.
Believe that a lot of people have encountered problems, how else can be in the forum to search for micro-letter payment can not actually solve the problem.

Add a callback, look at the code, and cover the following code to/lib/example/notify.php this file is OK

<?php ini_set (' Date.timezone ', ' Asia/shanghai ');
 
Error_reporting (E_error); Require_once ".
/lib/wxpay.api.php "; Require_once '..
/lib/wxpay.notify.php ';
Require_once ' log.php '; Initialize log $logHandler = new Clogfilehandler (". /logs/". Date (' y-m-d ').
Log ");
 
$log = Log::init ($logHandler, 15); Class Paynotifycallback extends Wxpaynotify {//Query order Public Function Queryorder ($transaction _id) {$in
        put = 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) &A
            mp;& $result ["return_code"] = = "SUCCESS" && $result ["result_code"] = = "SUCCESS") {
            $out _trade_no= $result [' out_trade_no '];//private order number, you use this order number to carry out various updates of your own order $mch _id= $result [' mch_id '];//merchant number] $total _fee= $result[' Total_fee '];//the amount to be paid, out of the amounts to be divided by the $transaction _id= $result [' transaction_id '];//micro-letter Internal Order Number $openid = $r  esult[' OpenID '];//micro-letter encryption of the user identity, the app to pay the words in fact, not very meaningful/* The following two lines used for debugging, will automatically generate In_test.txt files and later content will automatically append to this file * * * $fp =
            fopen (' In_test.txt ', ' A + '); Fwrite ($fp, Date ("Y-m-d h:i:s"). Json_encode ($result). "|". $transaction _id. "It worked!"
            RN ");
        /**/return true;//This very important, micro-letter asynchronous request, when you perform your internal processing after returning true to him, the micro-letter thought that your internal processing completed, will not ask you again, otherwise he will always request you this file, know timeout.
    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";
        return false;
            //Enquiry Order, Judge order authenticity if (! $this->queryorder ($data ["transaction_id"])) {$msg = "order query failed";
        return false;
 return true;   } Log::D ebug ("Begin Notify");
$notify = new Paynotifycallback ();
 
 $notify->handle (FALSE);

The above is the entire content of this article, I hope to help you learn.

Related Article

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.