Alipay paid from the front to the backstage

Source: Internet
Author: User
Tags aop

Recently took over a paid outsourcing project, both at the front desk and backstage, so I intend to take a few notes on this. Application

We have to do something to create an application before we have to pay for it.

sign up

This part of the contract requires real-name certification. I am following the signing of the completed, add the features you need, and then sign the certification waiting
generate public and private keys

Tool to generate public private key download address

According to my Arrow steps, the official website said it is best to use 2048, and then click "Generate Key", this time your generated key will be saved under the RSA key folder, if you want to use the next time, open the folder to find the application of public key 2048 or apply the private key 2048. (This tool in fact you can generate, want to generate on how to generate, as long as you guarantee that the public key you upload to the Alipay and your server configuration is the same as the public key, and the private key and the public key is matched on the line, the tool has a key matching option, you can match the test

the public key is uploaded to Alipay

Then we went on to the developer Center, found our new application, and chose the "Apply Info tab".

I've already set the public key for this place and you can set it up. Then the configuration is basically done.

Code Configuration Android Configuration

Where the code can look at this document, the permissions, inventory files, confusion, etc. are configured, and then we drive.

First of all, download the official website to the demo, to see the demo of the third party is still relatively easy to understand, we opened the Androiddemo, mainly to see Paydemoactivity.java this class

Paydemoactivity.java We look at paying this method, the others don't look anymore, no use

/** * Alipay Payment Business * * @param v/public void payV2 (View v) {/* Note, this part does not, for local test payments related to do not if (Textutils.isempty (APPID) | | (Textutils.isempty (rsa2_private) && textutils.isempty (rsa_private)) {New Alertdialog.builder (this). Settitle ("Warning"). Setmessage ("Need to configure AppID |
                        Rsa_private "). Setpositivebutton (" OK ", new Dialoginterface.onclicklistener () {
                            public void OnClick (dialoginterface dialoginterface, int i) {//
                        Finish ();
            ). Show ();
        Return * * */** * Here is only to facilitate the direct display of Alipay payment process, so the demo in the process of adding a signature directly on the client to complete; * Real app, Privatekey and other data is strictly prohibited on the client, plus signed 
       The process must be done on the service side (how thoughtful a word) * to prevent the merchant private data leakage, resulting in unnecessary loss of funds, and face various security risks; * * OrderInfo must be obtained from the service side;
        Boolean RSA2 = (rsa2_private.length () > 0); Map<string, string> params = Orderinfoutil2_0.buildorderparammap (APPID, RSA2);

        String Orderparam = Orderinfoutil2_0.buildorderparam (params); String Privatekey = rsa2?
        Rsa2_private:rsa_private;
        String sign = orderinfoutil2_0.getsign (params, privatekey, RSA2);

        Final String orderInfo = Orderparam + "&" + sign;
        * * This orderinfo we still need, Alipay request us this orderinfo back from the background to us, not in the foreground to generate, this payment demo is to give us a demonstration, this orderinfo generation, to complete the payment.
        So, we'll go backstage to get orderinfo in this place, and then we can go on to the next process.
        Android Configuration This part we pause, first to the background to configure something.
        * * Final String orderinfo= ""; Runnable payrunnable = new Runnable () {@Override public void run () {Paytask Ali
                Pay = new Paytask (paydemoactivity.this);
                map<string, string> result = Alipay.payv2 (OrderInfo, true);

                LOG.I ("MSP", Result.tostring ());
                msg = new Message ();
                Msg.what = Sdk_pay_flag; Msg.obj = ResULt
            Mhandler.sendmessage (msg);

        }
        };
        Thread paythread = new Thread (payrunnable);
    Paythread.start (); }
back-end PHP configuration

I use PHP backstage, in fact, the other configuration is the same, mainly look at the process.

Back-end Demo Download link, then we want to look at the PHP section of this document configuration, java. NET is such a process, the configuration of some information is basically OK.

I met some pits in this place, blaming myself for not noticing, listed to
(i), PHP version at least php5.5 the development environment
(b), go to the installation directory of PHP to find php.ini, open the file to find Extension=php_openssl.dll, go to the front of the semicolon, and then restart the server, because Alipay with the use of HTTPS to verify the return, so you need to open this.

All right. Look at the service-side code.

This is the demo sample from the official website, we follow this to

$AOP = new Aopclient;
$AOP->gatewayurl = "Https://openapi.alipay.com/gateway.do";
$AOP->appid = "app_id";
$AOP->rsaprivatekey = ' Please fill in the developer's private key to go to the end of the head to return, a line of string ';
$AOP->format = "json";
$AOP->charset = "UTF-8";
$AOP->signtype = "RSA2";
$AOP->alipayrsapublickey = ' Please fill out Alipay public key, one line string ';
Instantiate the specific API corresponding to the request class, class name and interface name corresponding to the current call Interface name: Alipay.trade.app.pay $request = new Alipaytradeapppayrequest (); The SDK has already encapsulated the public parameters, where only incoming business parameters $bizcontent = "{\ body\": \ "I am the test data \". "\ subject\": \ "app payment test \", "." \ "out_trade_no\": \ "20170125test01\", "." \ "Timeout_express\": \ "30m\", "." \ "total_amount\": \ "0.01\", "." \ "Product_code\": \ "Quick_msecurity_pay\".
"}";
$request->setnotifyurl ("asynchronous address accessible to merchant Extranet");
$request->setbizcontent ($bizcontent);
This is different from the ordinary interface call, using the Sdkexecute $response = $aop->sdkexecute ($request); Htmlspecialchars is to prevent the browser from escaping key parameter HTML in order to output to the page, actually printing to the log and the HTTP transmission will not have this problem echo htmlspecialchars ($Response);/is orderstring can be directly to the client request, no more processing. 

We create a new pay folder in the Alipay demo and create a new orderinfo.php file inside.

As shown in the figure:

In the new files and folders, we paste the code from the require_once and then introduce the class to be used below.

Or look at the code is comfortable, look at the picture is wrong.

<?php//This place to introduce the following to use the class require_once '.
/aop/aopclient.php '; Require_once '..


/aop/request/alipaytradeapppayrequest.php ';
$AOP = new Aopclient;
Here is the gateway, the following gateway is a formal environment, and so will configure the sandbox test environment will change a gateway $AOP->gatewayurl = "Https://openapi.alipay.com/gateway.do"; Fill in the AppId, in the application of the head has $AOP->appid = "app_id";/////This place fills in the private key, is we use the tool to generate the private key, this private key must be and uploads to Alipay's public key match, does not let, Alipay visit time will match the error $
Aop->rsaprivatekey = ' Please fill in the developer's private key to head to the tail to return, a line of string ';
$AOP->format = "json";
$AOP->charset = "UTF-8";
$AOP->signtype = "RSA2";
The public key of this place is the same, must be uploaded to the Alipay of the public key to the same $AOP->alipayrsapublickey = ' Please fill out Alipay public key, one line string ';
Instantiate the specific API corresponding to the request class, class name and interface name corresponding to the current call Interface name: Alipay.trade.app.pay $request = new Alipaytradeapppayrequest (); The SDK has already encapsulated the public parameters, where only incoming business parameters are required $bizcontent = "{\" body\ ": \" I am testing data \ ","//This place to write some parameters, in the pop-up payment will show. "\ subject\": \ "app payment test \", "//This can be paid for some of the description." \ "out_trade_no\": \ "20170125test01\", "//order number, must be unique, etc I'll give a function to generate the order number,." \ "Timeout_express\": \ "30m\", "." \ "Total_amoUnt\ ": \ 0.01\", "." \ "Product_code\": \ "Quick_msecurity_pay\".
"}";
$request->setnotifyurl ("asynchronous address accessible to merchant Extranet");
$request->setbizcontent ($bizcontent);
This is different from the ordinary interface call, using the Sdkexecute $response = $aop->sdkexecute ($request); Htmlspecialchars is to prevent the browser from escaping key parameter HTML in order to output to the page, actually printing to the log and HTTP transmission will not have this problem echo htmlspecialchars ($response); Is that orderstring can be directly to the client request, no more processing.

Insert a little thing, order number generate code

function order ()
{
    $yCode = array (' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ');
    $orderSn = $yCode [Intval (Date (' Y ')]-2011]. Strtoupper (Date (' M ')) (Dechex). Date (' d '). SUBSTR (Time (),-5). SUBSTR (Microtime (), 2, 5). sprintf ('%02d ', rand (0));
    return $orderSn;
}

After completing, let's test and visit this link to see what's returned.

app_id=2016080601711375&biz_content=%7b%22body%22%3a%22%e6%88%91%e6%98%af%e6%b5% 8b%e8%af%95%e6%95%b0%e6%8d%ae%22%2c%22subject%22%3a+%22app%e6%94%af%e4%bb%98%e6%b5%8b%e8%af%95%22%2c%22out_ trade_no%22%3a+%2220170125test01%22%2c%22timeout_express%22%3a+%2230m%22%2c%22total_amount%22%3a+%220.01%22%2c %22product_code%22%3a%22quick_msecurity_pay%22%7d&charset=utf-8&format=json&method= alipay.trade.app.pay&notify_url=http%3a%2f%2fwww.inbandian.com%2f&sign_type=rsa2&timestamp= 2017-04-07+20%3a13%3a33&version=1.0&sign= uyy7kk7jz4znsla1vwasev0mrcmmzt2dcfdxu9hwckc0hyqjzdsu6c97anp062xji0yogqcxhtblaescnwj% 2fkknejqelfpn3gaave0aexeiirukclx1lxpmmvhotcwx% 2fdlgsqvtrlyvsheoobcib8avxvpknnb4cezsog7r4ee7rn8tbjz46pdo786u9hbmurddgvn753j4yotruuj2ygpl1seauueostfdbrhkbefwxu %2btrbrgejreps0vz2hcnblkoag9rmx4gtwkgxv0eoqb%2fpcjjbsklfkviwo9vs1nxnfwso%2fxqk% 2frv37zftvrvgrpqhuxnzhveuxobqbqm2g%3d%3d 

believe that the format of the printed order information that is paid on the Android side and paid directly on the Android side must be the same as this one, right?

Well, the link is also tested through, so we only need to go through the Android side, each time payment, through this interface to get order information, and then this information through the Alipay API

map<string, string> result = Alipay.payv2 (OrderInfo, true);

Can be paid, below I give the simple Android end code.

public class Paydemoactivity extends Fragmentactivity {private static final int sdk_pay_flag = 1;

    private static final int sdk_auth_flag = 2; @SuppressLint ("Handlerleak") private Handler Mhandler = new Handler () {@SuppressWarnings ("unused") pu Blic void Handlemessage (msg) {switch (msg.what) {case Sdk_pay_flag: {@S
                Uppresswarnings ("unchecked") payresult Payresult = new Payresult ((map<string, string>) msg.obj); /** for payment results, ask the merchant to rely on the server-side asynchronous notification results.
                 Synchronize the notification results only as a notification of payment completion. */String Resultinfo = Payresult.getresult ();//sync returns the information that needs to be validated string resultstatus = Payresul
                T.getresultstatus (); The Judge Resultstatus 9000 is the payment success if (Textutils.equals (Resultstatus, "9000")) {//whether the order
                    True payment success requires the reliance of asynchronous notifications on the server side. Toast.maketext (Paydemoactivity.this, "pay success", Toast.length_shoRT). Show ();
                    else {//The actual payment result of the order requires an asynchronous notification on the server side.
                Toast.maketext (Paydemoactivity.this, "Payment failure", Toast.length_short). Show ();
            } break;
    }
        };

    };
        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.pay_main); /** * Alipay Payment Business * * @param v */public void payV2 (View v) {Runnable payrunnable = n
                EW Runnable () {@Override public void run () {URL url = null;
                    try {url = new URL ("orderinfo.php URL address");
                    HttpURLConnection conn = (httpurlconnection) url.openconnection ();
                    BufferedReader br = new BufferedReader (New InputStreamReader (Conn.getinputstream ()));
                    String orderInfo = "";

                String Len;    while (len = Br.readline ())!= null) {orderInfo + = Len; } log.i ("OrderInfo", orderInfo);//print to see if it's right paytask Alipay = new Paytask (paydemoactivity
                . this);


                map<string, string> result = Alipay.payv2 (OrderInfo, true);

                LOG.I ("MSP", Result.tostring ());
                msg = new Message ();
                Msg.what = Sdk_pay_flag;
                Msg.obj = result;
            Mhandler.sendmessage (msg);
            }catch (Exception e) {e.printstacktrace ();

        }
            }
        };
        Thread paythread = new Thread (payrunnable);
    Paythread.start (); }
}

The code is quite small, so that the front-end and back-end to get through, and then pay the successful asynchronous notification server What, you can play the idea of everyone (anyway I have done, awesome, haha).

Everyone in the test time to think, every time I use 0.01 to test data, is a bit of a pit ah, love my money ah, just started not understand when I recharge several times, the meat hurts.

Okay, here's the procedure for the sandbox test, which basically means, Alipay will provide you with a sandbox test account password, but also the designated sandbox version of Alipay app, we go to download this Alipay app, and then landed Alipay to our account, there are buyers and merchants account has, and then test, Will arouse our this sandbox version of Alipay, play up and true Alipay is the same. sandbox version Alipay test

Since it is used for testing, unavoidable configuration, sandbox version of the configuration and the previous application configuration is identical. Look at the steps. Configuration

First of all, go into the developer center, such as the figure, select Sandbox application.

And the previous configuration is not so little like it, Haha, the sandbox version of the Alipay gateway and the real environment is not the same, we will go to replace him, there are appid, the following key configuration and the previous steps like, open the key tool, randomly generated a 2048 key, the public key posted.

We continue to slide down, there will be a sandbox version of the app's two-dimensional code, we scan and download him down.

Okay, now we're going to create a new sandboxorderinfo.php in the Pay folder in the server-side folder.

<?php//This place to introduce the following to use the class require_once '.
/aop/aopclient.php '; Require_once '..


/aop/request/alipaytradeapppayrequest.php ';
$AOP = new Aopclient;
Here is the gateway, fill in the sandbox version of the gateway $AOP->gatewayurl = "Https://openapi.alipay.com/gateway.do"; Fill in the AppId, fill in the sandbox version of the appId $aop->appid = "app_id";////This place fills in the private key, that is, the private key that we generate with the tool above, this private key must be to match with the public key that uploads to Alipay, not let,
Alipay visit will match the error $aop->rsaprivatekey = ' Please fill out the developer's private key to head to the tail to return, a line of string ';
$AOP->format = "json";
$AOP->charset = "UTF-8";
$AOP->signtype = "RSA2";
The public key of this place is the same, must be uploaded to the Alipay of the public key to the same $AOP->alipayrsapublickey = ' Please fill out Alipay public key, one line string ';
Instantiate the specific API corresponding to the request class, class name and interface name corresponding to the current call Interface name: Alipay.trade.app.pay $request = new Alipaytradeapppayrequest (); The SDK has already encapsulated the public parameters, where only incoming business parameters are required $bizcontent = "{\" body\ ": \" I am testing data \ ","//This place to write some parameters, in the pop-up payment will show. "\ subject\": \ "app payment test \", "//This can be paid for some of the description." \ "out_trade_no\": \ "20170125test01\", "//order number, must be unique, etc I'll give a function to generate the order number,." \ "Timeout_express\": \ "30m\", "." \ "total_amount\": \ "0.01\","
                . "\ product_code\": \ "Quick_msecurity_pay\".
"}";
$request->setnotifyurl ("asynchronous address accessible to merchant Extranet");//This asynchronous address is the $request->setbizcontent ($bizcontent) that you configure in my application in the developer Center;
This is different from the ordinary interface call, using the Sdkexecute $response = $aop->sdkexecute ($request); Htmlspecialchars is to prevent the browser from escaping key parameter HTML in order to output to the page, actually printing to the log and HTTP transmission will not have this problem echo htmlspecialchars ($response); Is that orderstring can be directly to the client request, no more processing.

This is just like the environment before, just modify the app_id, the gateway, and the corresponding public and private keys on the line. Well, the server is well configured.

Let's open the "sandbox account" in the developer Center. As shown in figure

Sandbox will give us a merchant's and buyer's account, for us to test, see recharge that option did not, really seems to be my real account ah, want how much on their own fill, good. Then we use this account to login to our sandbox version of the app, landing success we do not need to take care of him, as he is we are really Alipay account.

Then back to our Android client, we added a code to OnCreate initialization, telling Alipay that we were in a sandbox environment.

@Override
    protected void onCreate (Bundle savedinstancestate) {
        super.oncreate (savedinstancestate);
        Setcontentview (r.layout.pay_main);
        Envutils.setenv (EnvUtils.EnvEnum.SANDBOX);
    }

Then we will access the URL to get the order information to sandboxorderinfo.php, and then access to get, to pay, OK, done. How to pay if you want to pay, good.

The front-end to the back end of the combination is quite simple, followed by the idea of a routine, Java and ASP are the same.

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.