Alipay integration Process--run demo

Source: Internet
Author: User
Tags openssl openssl rsa

Preface, The Dream is to insist on, on the road, all the way forward. Come on.


These two days the software needs to integrate Alipay, the first integration, the process is quite simple, but due to the official document of Alipay is not clear enough, but also to go some detours, the following process to share to everyone


first, apply for mobile payment permission

First login to "Alipay open platform" http://open.alipay.com/platform/home.htm, add apps, apply for mobile payment permissions. To apply for an open payment, the company documents are required, and individuals are not allowed to start paying.
Details will not be discussed in detail, the following talk about how to the Ali given the demo run up.
second, Ali pay demo 1. Overview (1) Payment call page and test

Alipay in the call, will first look at the local is not existing Alipay client, if any, directly call the client to pay, if not, then call the jar package in the H5 page payment.
So when testing, there are two scenarios that need to be tested: There are Alipay clients and no Alipay clients.

(2), client and server in the demo you can see, there is a client's demo also has a service side of the demo, you may feel the need to write a good service, the client can be integrated, in fact, not. The whole process is this:
1,app client sends payment request via SDK (client processing)
2,SDK payment succeeds and returns the payment result synchronously (client processing)
3, Alipay server sends a payment result string to our server (service-side processing)
Client: From the above process, it can be seen that the server is only used to answer the payment results of the asynchronous return. and the payment and the results of the synchronization are returned to the client can be directly seen. So when integrated Alipay payment interface, the main function is on the client, even if the service side does not do integration, it is possible to pay successfully.
Server: Server only need to add a function: interface payment results returned

The following diagram shows the entire demo running process, because there is no way to record a GIF on the real machine, so you can only use the picture instead.
Initialize the interface:

After clicking Pay, jump out of the confirmation payment screen:


After clicking confirm Payment, jump out of the input password screen:


Finally the payment Success screen:


Before we look at the demo code, we need to configure a few variables:
2, configure a few variables This section will be used in the code to find a few variables or generate methods to tell, some of the data from Alipay open platform.
(1) PID

The Partner Identity ID (PID) is the merchant's unique identification number after signing up with Alipay for the merchant's Alipay merchant. When the merchant uses Alipay to access the merchant website, the PID is used to allow Alipay to authenticate the merchant.
View the PID steps as follows:
1. Login to Alipay official website b.alipay.com
2. Click "Merchant Services" in the navigation bar.


3. Click "Query pid, Key"


(2), APPID, app secret and Alipay public key on https://openhome.alipay.com/platform/createApp.htm page, create an app


After completion: It can be seen in my app:


Then go to the Account basic Information page: https://openhome.alipay.com/platform/keyManage.htm


In the open Platform key bar, you can find Appid,app SECRET, and Alipay key
These three data, after the application has been created, Alipay for us to generate good, cannot change.

(3), generate the Merchant private key "Windows Generation Method"(for Mac generation method, the following will be added)
1. Download demo and SDK
To the document center, view the document for the mobile payment, document address: http://doc.open.alipay.com/doc2/detail?treeId=59&articleId=103563&docType=1
Then, click (sdk&demo download) to download the code


2. Get the original private key
In the code, under the Demo/openssl/bin directory, there are openssl.exe files


Open Openssl.exe
Input

Genrsa-out RSA_PRIVATE_KEY.PEM 1024
Get the result of the build success, as shown below:

At this point, we can see a file named Rsa_private_key.pem in the Bin folder


To open it in Notepad, you can see-----begin with the RSA private key-----,-----End of the RSA private key-----No newline string, this is the original private key.


But this is not in the original private key code, we need to convert it to PKCS8 format
3. Convert to PKCS8 format
Enter in Openssl.exe: and return

Pkcs8-topk8-inform pem-in Rsa_private_key.pem-outform Pem-nocrypt
To get the result of the success, the result is the private key in the PKCS8 format, as shown below:


Note that the private key is the part of the red box that does not contain the two lines of begin private key and end private key.

Right-click the top edge of the OpenSSL window, select edit → tag, select the text you want to copy (above),
Now continue right click on the top edge of the OpenSSL window, select edit → copy,
The copied content clay into a new Notepad, can be casually named, as long as you know this is the PKCS8 format of the private key.
(4), Generate merchant private key "Mac Generation Method"

Here's how the Mac side generates the user's private key, because the Mac system comes with OpenSSL, so just open the terminal and use the CD command to cut to any folder where you want to store the generated key:
For example, cut to the download directory


Then run the following command to generate the private key original key

OpenSSL genrsa-out Rsa_private_key.pem 1024
Then run the following command to generate the converted PCKS8 Format command.
OpenSSL pkcs8-topk8-inform pem-in rsa_private_key.pem-outform pem-nocrypt
The resulting private key copy is then saved.
As can be seen from the above command, the MAC needs to be added in front of the OpenSSL specified in the previous session to run the. The other commands are exactly the same.
(5), generate user Public key and page fill 1. Generate Public key
Also for Windows users, enter the following command directly in the Openssl.exe:
Rsa-in Rsa_private_key.pem-pubout-out Rsa_public_key.pem
Similarly, if you are a classmate of Mac, you should enter the following command:
OpenSSL rsa-in rsa_private_key.pem-pubout-out Rsa_public_key.pem
Get the result of the build success, as shown below:

At this point, we can see in the Bin folder a file named Rsa_public_key.pem, open it in Notepad, you can see-----begin public Key-----start,
-----End of the public key-----The string with no newline, this is the key.



After the Web page is generated, copy----the part between the begin public key-----and-----End public key-----, that is, the plain code, do not----BEGIN public key-----and-----END Public The KEY-----copied in. This part of the middle is the public key.
2. Page Fill
Then go to Https://openhome.alipay.com/platform/keyManage.htm?keyType=partner (login required), find the partner key bar on the left, and then to the RSA encryption on the right, paste the public key in. Because, we have pasted in, so here to see the developer public key, before filling in the "Add developer Public key"


Here, all the preparations are over. Here is the process of configuring the demo
3, configure the demo in the source of the Sdk&demo just downloaded, open demo/client demo/Alipay android 15.0.1/alipay_demo Project
The path is as follows:


Configure several variables in the paydemoactivity:

PID public
static final String PARTNER = "";
Fill in here the PID we found above;
Merchant Collection Account public
static final String SELLER = "76949XXXX@qq.com";
Then write our Alipay login account on the seller, which is the Alipay account you applied for the mobile payment.
Alipay public key publicly
static final String rsa_public = "";
and fill in the Alipay public key here at Rsa_public.
Merchant private key, PKCS8 format public
static final String rsa_private = "";
Finally, fill in the rsa_private corresponding merchant private key, note is in PKCS8 format.
In this part of the private key, note that the section between the----begin public key-----and-----END Public key-----, that is, the pure code, do not----BEGIN public key-----and-----END Public The KEY-----copied in. This part of the middle is the public key.

Now run the demo to pay directly.

The corresponding demo in this article is given at the bottom of the article. 4, the code explained through the above configuration, the demo should be able to run directly, but here the code involved, we take a closer look at
The main payment and result return is the pay () function, where all the functions required for payment are completed. The code is as follows:

public void Pay (View v) {
	...
	... Order information
	String orderInfo = GetOrderInfo ("Tested commodity", "detailed description of the test commodity", "0.01");

	Make an RSA signature on the order
	String sign (orderInfo);
	try {
		//Just URL-encode sign
		= Urlencoder.encode (sign, "UTF-8");
	} catch (Unsupportedencodingexception e) { C9/>e.printstacktrace ();
	}

	Complete order information in accordance with Alipay specifications
	Final String payinfo = orderInfo + "&sign=\" "+ sign +" \ "&"
			+ Getsigntype ();

	Runnable payrunnable = new Runnable () {

		@Override public
		void Run () {
			//Construct Paytask object
			paytask Alipay = New Paytask (paydemoactivity.this);
			Call the payment interface to get the result of the payment
			String results = Alipay.pay (payinfo);

			Message msg = new Message ();
			Msg.what = Sdk_pay_flag;
			Msg.obj = result;
			Mhandler.sendmessage (msg);
		}
	};

	The
	thread paythread = new Thread (payrunnable) must be called asynchronously;
	Paythread.start ();
}

There are always four steps to complete payment and result reception.

First step: Construct the order information:

String orderInfo = GetOrderInfo ("Tested commodity", "detailed description of the test commodity", "0.01");
This is the main sentence, that is, in the GetOrderInfo () function to complete the construction of order information: (here to getorderinfo function to do the refinement, more fields and meaning reference source)

For Paymethod method use, refer to: https://cshall.alipay.com/support/help_detail.htm?help_id=476935
The meaning and value of each field reference: http://doc.open.alipay.com/doc2/detail?treeId=59&articleId=103663&docType=1

public string GetOrderInfo (string subject, string body, string price) {

	//contracted partner Identity ID
	String orderInfo = "partner=" + "\" "+ PARTNER +" \ "";

	Contract Seller Alipay Account
	OrderInfo + = "&seller_id=" + "\" "+ Seller +" \ "";

	Merchant website Unique order number
	OrderInfo + = "&out_trade_no=" + "\" "+ Getouttradeno () +" \ "";

	Product Name
	OrderInfo + = "&subject=" + "\" "+ Subject +" \ "";

	Product Details
	OrderInfo + = "&body=" + "\" "+ Body +" \ "";

	Product Amount
	OrderInfo + = "&total_fee=" + "\" "+ Price +" \ "";

	Server Asynchronous Notification page path
	orderInfo + = "&notify_url=" + "\" "+" http://notify.msp.hk/notify.htm "
			+" \ "";
	....... return orderInfo;
}
Here is to construct the order and callback page through our provided business ID, product information, price and other information, here is a very important place to pay attention to:
Server Asynchronous Notification page path
orderInfo + = "&noify_url=" + "\" "+" http://notify.msp.hk/notify.htm "
		+" \ "";
Server Asynchronous Notification page path, first we pay by Alipay after payment, Alipay will return to us two notifications, one is synchronous, is we click to pay Alipay direct feedback to our client's information, we can directly get, according to the results of the feedback can be initially judged whether the transaction is successful, The second is the server asynchronous notification, this asynchronous notification is the server side of the Alipay to send us the server side of the information, we are directly in the client can not get, the Alipay server how to know the path of our server, that is the role of this parameter, we give the Alipay server a path, It will give us a server feedback when the order status changes, tell the server the status of this transaction, if the server results determine that the transaction is successful, you must return to the Alipay Server a success, or the server will always give us an asynchronous notification, because it does not know whether the transaction is completed ( Generally 8 times within 25 hours of notification, frequency is generally 2m 10m 10m 1h 2h 6h 15h), we generally receive an asynchronous notification, the status of the order to update.
Others do not speak, by looking at the source code can be understood, such as the construction of order number what.

The second step: the order string to do RSA signature why to sign it. Of course is to prevent transmission error, this is related to money, if the OrderInfo transmission process error, then how to verify it is not a mistake, only through the signature algorithm. So here we need to sign the order string.
Specific signature algorithm does not speak, directly applied to the project on the line, do not need to understand, if you want to see how to achieve, there are corresponding source code, you can go to study.

Make an RSA signature on the order
String sign (orderInfo);
try {
	//Just URL-encode sign
	= Urlencoder.encode (sign, "UTF-8");
} catch (Unsupportedencodingexception e) { C6/>e.printstacktrace ();
}
Step Three: Construct the completed request stringAfter the order string and signature have been completed, they can be used to construct the complete request string:
Complete order information in accordance with Alipay specifications
Final String payinfo = orderInfo + "&sign=\" "+ sign +" \ "&"
		+ Getsigntype ();
Fourth Step: request and result returnFinally, the request is sent with the following code:

Runnable payrunnable = new Runnable () {

	@Override public
	void Run () {
		//Construct Paytask object
		paytask Alipay = new Paytask (paydemoactivity.this);
		Call the payment interface to get the result of the payment
		String results = Alipay.pay (payinfo);

		Message msg = new Message ();
		Msg.what = Sdk_pay_flag;
		Msg.obj = result;
		Mhandler.sendmessage (msg);
	}
};

The
thread paythread = new Thread (payrunnable) must be called asynchronously;
Paythread.start ();
The most critical parts are here:
Paytask Alipay = new Paytask (paydemoactivity.this);
Call the payment interface to get the result of the payment
String results = Alipay.pay (payinfo);

Message msg = new Message ();
Msg.what = Sdk_pay_flag;
Msg.obj = result;
Mhandler.sendmessage (msg);
In string result = Alipay.pay (payinfo), the payment result is obtained directly;
The results are then sent out via handler.
This is how you get paid results in a synchronized way.
All right, the method of Alipay docking is all here. As for the GetOrderInfo function, the use of the calling card to pay, I think there is no use, in our program also did not pick up.


This article is used by the demo source download address: http://download.csdn.net/detail/harvic880925/9261363


If this article has helped you, remember to add attention to OH.

Please respect the original copyright, reproduced please indicate the source: http://blog.csdn.net/harvic880925/article/details/49779061 Thank you.

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.