Alipay access

No nonsense, directly explain Alipay access from the developer's point of view.

First of all, Alipay has two versions of Alipay payment interface, temporarily called the old version 1.0 and the new version 2.0. Since our PC is connected to version 1.0, I also get 1.0 here.

The main difference between the two versions is that the request parameters when calling the payment interface have changed, and the rest of the process is roughly the same.

1.0 official document address: https://doc.open.alipay.com/doc2/detail?treeId=59&articleId=103563&docType=1

2.0 official document address: https://doc.open.alipay.com/

2.0 document entry screenshot:


2.0 Document points and SDK download


The following is a detailed introduction to Alipay 1.0 Android terminal access.

1. Before development: it may be because of the customer's suggestion or the original needs of the arrangement or the order of the big leader. In short, the product manager has spoken, we are going to connect to AlipaySmile

First of all, the relevant departments of the company apply to Alipay and go through the contract review. Then Alipay provides us with some keys. We need to use the tools provided in the Alipay documentation to generate our own private key and public key, upload the public key to Alipay and download the Alipay public key. In fact, these steps need to be processed by our company's server, as well as the subsequent generation of orders and signatures. What needs to be done only for Android side development is very simple. But it doesn't hurt to know the general process. And it is possible that sometimes the server is also ourselves, so we must know this.

2. Preparatory work before access:

Key configuration and management: Click Quick Access on the above 1.0 official document address page, and then click Key Function in the pre-access preparation stage to enter the following figure. You can follow the steps indicated in the document to obtain the merchant PID, generate the private key and public key, and some instructions for uploading the public key.

   

          SDK and demo sample download: Click the resource download in the 1.0 document. After decompressing the downloaded compressed package, open it, including the server demo and client demo, both Android and IOS. We just need to find what we use. Unzip (Alipay wallet payment interface development kit standard version (Android...)), after unzipping, it includes an SDK jar package and a demo example, the demo is very simple and can be imported into the development tool to have a look.

3. The specific access process:

  Click for a detailed explanation of the integration process, including IOS access process and Android access process

    Follow the process to import the jar package and then Build Path, add permissions and declarations in the Manifest, add obfuscation rules, and then look at the code.

package com.alipay.sdk.pay.demo;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import com.alipay.sdk.app.PayTask;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

public class PayDemoActivity extends FragmentActivity {

	// Merchant PID
	public static final String PARTNER = "2088********8050";
	// Merchant payment account
	public static final String SELLER = "2088********8050";
	// Merchant private key, pkcs8 format
	public static final String RSA_PRIVATE = "MIICd*************************";
	// Alipay public key
	public static final String RSA_PUBLIC = "";
	private static final int SDK_PAY_FLAG = 1;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * The results returned synchronously must be placed on the server for verification (see https://doc.open.alipay.com/doc2/ for verification rules
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) It is recommended that merchants rely on asynchronous notifications
				 */
				String resultInfo = payResult.getResult();// Synchronously return the information that needs to be verified

				String resultStatus = payResult.getResultStatus();
				// Judging that the resultStatus is "9000" means the payment is successful. For the meaning of the specific status code, please refer to the interface documentation
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(PayDemoActivity.this, "Successful payment", Toast.LENGTH_SHORT).show();
				} else {
					// Judging that resultStatus is not "9000" means that the payment may fail
					// "8000" means that the payment result is still waiting for payment result confirmation due to payment channel or system reasons. Whether the final transaction is successful or not is subject to the asynchronous notification from the server (small probability status)
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(PayDemoActivity.this, "Payment result confirmation", Toast.LENGTH_SHORT).show();

					} else {
						// Other values ​​can be judged as payment failure, including the user's initiative to cancel the payment, or the error returned by the system
						Toast.makeText(PayDemoActivity.this, "Payment failed", Toast.LENGTH_SHORT).show();

					}
				}
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView(R.layout.pay_main);
	}

	/**
	 * call alipay sdk pay. Call SDK to pay
	 *
	 */
	public void pay(View v) {
		if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE) || TextUtils.isEmpty(SELLER)) {
			new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface, int i) {
							//
							finish();
						}
					}).show();
			return;
		}
		String orderInfo = getOrderInfo("Tested item", "Detailed description of the tested item", "0.01");

		/**
		 * Special attention, the signature logic here needs to be placed on the server side, do not leak the private key in the code!
		 */
		String sign = sign(orderInfo);
		try {
			/**
			 * Only need to URL encode sign
			 */
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace ();
		}

		/**
		 * Complete order information that complies with Alipay parameter specifications
		 */
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// Construct the PayTask object
				PayTask alipay = new PayTask(PayDemoActivity.this);
				// Call the payment interface to get the payment result
				String result = alipay.pay(payInfo, true);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// must be called asynchronously
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * get the sdk version. Get the SDK version number
	 *
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * Native H5 (mobile web version payment cut natvie payment) [corresponding page web page payment button]
	 *
	 * @paramv
	 */
	public void h5Pay(View v) {
		Intent intent = new Intent(this, H5PayDemoActivity.class);
		Bundle extras = new Bundle();
		/**
		 * The url is the test website, the page opened inside the app is opened based on the webview, the webview in the demo is H5PayDemoActivity,
		 * The logic of intercepting url for payment in the demo is implemented in the shouldOverrideUrlLoading method in H5PayDemoActivity.
		 * Merchants can implement according to their own needs
		 */
		String url = "http://m.taobao.com";
		// The url can be a third-party shopping wap site such as Yihaodian or Taobao. During the payment process of the website, Alipay SDK completes the interception of payment
		extras.putString("url", url);
		intent.putExtras(extras);
		startActivity(intent);
	}

	/**
	 * create the order info.
	 *
	 */
	private String getOrderInfo(String subject, String body, String price) {

		// Signing partner ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// Sign the seller's 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 + "\"";

		// The amount of goods
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// The server notifies the page path asynchronously
		orderInfo += "¬ify_url=" + "\"" + "http://notify.msp.hk/notify.htm" + "\"";

		// service interface name, fixed value
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// payment type, fixed value
		orderInfo += "&payment_type=\"1\"";

		// parameter encoding, fixed value
		orderInfo += "&_input_charset=\"utf-8\"";

		// Set the timeout for unpaid transactions
		// The default is 30 minutes. Once the timeout expires, the transaction will be automatically closed.
		// Value range: 1m~15d.
		// m-minutes, h-hours, d-days, 1c-days (closes at 0 no matter when the transaction was created).
		// The value of this parameter does not accept decimal points, such as 1.5h, which can be converted to 90m.
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token is the alipay_open_id obtained by Kuaideng authorization, with this parameter the user will use the authorized account to pay
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// After Alipay processes the request, the current page jumps to the path of the page specified by the merchant, which can be empty
		orderInfo += "&return_url=\"m.alipay.com\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. Generate a merchant order number, this value should be unique on the merchant side (customizable format specification)
	 *
	 */
	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt ();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info.
	 *
	 * @param content
	 * Order information to be signed
	 */
	private String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use.
	 *
	 */
	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

}

As long as we carefully understand the code of this class, we can almost understand the calling process. When constructing the PayTask object to call the payment interface, a new thread must be opened, and then the returned result is received in the handler.

Here is a description of the parameters used to remove the Alipay interface. In the sample code, we can see that only two parameters are passed when calling the payment interface, payInfo and a boolean value. PayInfo is the merchant id we added: PARTNER (starting with 2088) 16-digit string), merchant collection account: SELLER's order information, the signed and encrypted string of this order information, and the string concatenated by the signature method. The boolean value indicates whether a buffer frame is needed when calling the interface, and directly pass true.

Now let's take a look at the functional flow chart of our interaction with Alipay:

Note that there is a parameter notify_url         when splicing order information

      For the completed transaction, Alipay will feed back the data to the merchant client and the merchant server in two ways.

  1. On the mobile client, the mobile Alipay payment development kit directly feeds back the processed data results to the merchant client;
  2. On the server side, the mobile Alipay payment server side actively initiates a notification and calls the page path set by the merchant at the time of the request (the parameter notify_url, if the merchant does not set it, this operation will not be performed).

After the access process is fully understood, is it so easy to integrate Alipay payment in your own project?


ps: If the division of labor between the APP development server and the mobile terminal of your company is clear, the Android engineer only needs to import the jar package to configure the basic configuration required to access Alipay in the project, and then pass the basic order information to the server to wait for the return to call the payment interface. The entire string is just fine.

                                                                                      

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326441065&siteId=291194637