Quickstart

This quickstart guides you through the integration process of Cashier Payment using Alipay+ APIs.

Set up the server
Server-side
(Optional) Add dependency

If you use the JAR file provided by Alipay+, add the dependency to your project.

Add Maven dependency:
1<dependency>
2  <groupId>com.alipay.global.sdk</groupId>
3  <artifactId>global-open-sdk-java</artifactId>
4  <version>2.0.11</version>
5</dependency>
Configure requests

To configure requests, obtain the following information first:

  • Log in to Alipay+ Dashboard. Go to Developers > Quickstart, find Integration resources, and get the following details:
    • Gateway domain name
    • Client ID
    • API keys: You need to generate keys yourself. For more information about how to generate or replace keys, see API key configuration.
  • API path: Get the path for a specific API in Alipay APIs.

Then configure the obtained gateway domain name, Client ID, API keys, and API path to your API request.

Note: If you use the JAR file provided by Alipay+, you can use the codes directly without additional processing. If you prefer to sign a request and verify the signature by yourself, see Sign a request and verify the signature.

Set up a HTTPS request:
1String domain = "DOMAIN"
2String merchantPrivateKey = "YOUR PRIVATE KEY";
3String alipayPublicKey = "ALIPAY PUBLIC KEY"
4AlipayClient defaultAlipayClient = new DefaultAlipayClient(domain, merchantPrivateKey, alipayPublicKey);
5
6AlipayPayRequest alipayPayRequest = new AlipayPayRequest();
7alipayPayRequest.setClientId(CLIENT_ID);
8alipayPayRequest.setPath(API_PATH);
Create a checkout page
Client-side

Create a checkout page on your client to display the goods ID, order information, available payment methods, the payment button, and other payment information.

Add payment methods

Add payment methods on your checkout page:

Note: For Alipay+ payment methods, you must display the Alipay+ Partner logo as in the picture.

Display of Alipay+ payment methods:
Initiate a payment
Server-side

When initiating a pay request, you need to pass in the following URLs:

  • paymentRedirectUrl: Your payment result page URL. Alipay+ redirects the buyer to this URL after the payment is completed. Pass in the required redirect URL types for different client-side terminals:
    • Web: Pass in a PC website redirect URL.
    • WAP: Pass in a web URL redirect URL.
    • App: Pass in a deep link URL.
  • paymentNotifyUrl: Alipay+ sends the payment and capture results to this URL after the payment and capture reaches a final status. Specify paymentNotifyUrl as an HTTPS URL and make sure that the URL can receive notifications.

After the buyer clicks the payment button, initiate the pay request using the alipayPayRequest object created in the Configure requests step.

Refer to samples in the code editor according to the following different payment types:

  • Non-card payment: includes payments of the following payment method categories:
    • Alipay+
    • Wallet
    • Online banking
    • Bank transfer
    • Mobile banking app
  • Card Payment (hosted payment page mode): In this mode, Alipay+ provides a page for collecting card payment information. If the buyer chooses to save the card on the page, Alipay+ stores the buyer's card information and generates a corresponding card token (cardToken). You can use the card token for future payments.
  • Card Payment (server-to-server mode): This mode requires that you are PCI-qualified.

Additionally, for card payments, when sending a pay request, you can also choose whether to use value-added features according to your business needs.

For specific payment requirements of different payment methods, see the pay API.

Order information:
1// set order Info
2Order order = new Order();
3
4// replace with your orderId
5String orderId = UUID.randomUUID().toString();
6
7order.setReferenceOrderId(orderId);
8order.setOrderDescription("Test Order");
9order.setOrderAmount(amount);
10Buyer buyer = new Buyer();
11buyer.setReferenceBuyerId("Your Buyer Id");
12order.setBuyer(buyer);
13order.setOrderAmount(amount);
14alipayPayRequest.setOrder(order);
Environment information:
1// set env Info
2Env env = new Env();
3env.setTerminalType("WEB");
4env.setClientIp("YOUR CUSTOMER IP");
5alipayPayRequest.setEnv(env);
6order.setEnv(env);
Payment information:
1// set amount
2Amount amount = new Amount();
3amount.setCurrency("BRL");
4amount.setValue("4200");
5alipayPayRequest.setPaymentAmount(amount);
6
7//set settlement currency
8SettlementStrategy settlementStrategy = new SettlementStrategy();
9settlementStrategy.setSettlementCurrency("USD");
10alipayPayRequest.setSettlementStrategy(settlementStrategy);
11
12// replace with your paymentRequestId
13String paymentRequestId = UUID.randomUUID().toString();
14alipayPayRequest.setPaymentRequestId(paymentRequestId);
15
16// set paymentMethod
17PaymentMethod paymentMethod = new PaymentMethod();
18paymentMethod.setPaymentMethodType("GCASH");
19alipayPayRequest.setPaymentMethod(paymentMethod);
20
21// set productcode
22alipayPayRequest.setProductCode("CASHIER_PAYMENT");
Card information (server-to-server mode):
1//if merchant collect card info, set card info in this paymentMethodMetaData
2Map<String, Object> paymentMethodMetaData = new HashMap<String, Object>();
3paymentMethodMetaData.put("cardNo", "0255187751531899");
4paymentMethodMetaData.put("cvv", "712");
5paymentMethodMetaData.put("expiryMonth", "06");
6paymentMethodMetaData.put("expiryYear", "28");
7paymentMethodMetaData.put("tokenize", false);
8JSONObject cardholderName = new JSONObject();
9cardholderName.put("firstName", "Alan");
10cardholderName.put("lastName", "Wallex");
11paymentMethodMetaData.put("cardholderName", cardholderName);
12paymentMethod.setPaymentMethodMetaData(paymentMethodMetaData);
Card authorization (Card payments):
1// set authorization
2paymentFactor.setAuthorization(true);
3alipayPayRequest.setPaymentFactor(paymentFactor);
Payment redirect URL:
1// replace with your redirect url
2alipayPayRequest.setPaymentRedirectUrl("http://www.yourRedirectUrl.com");
Payment notification URL:
1// replace with your notify url
2alipayPayRequest.setPaymentNotifyUrl("http://www.yourNotifyUrl.com");
Signing a request:
1private String genSignValue(String httpMethod, String path, String clientId, String requestTime, String reqBody) throws AlipayApiException {
2    String signatureValue;
3    try {
4        String reqContent = httpMethod + " " + path + "\n" + clientId + "." + timeString
5        + "." + content;
6        signatureValue = encode(signWithSHA256RSA(reqContent, merchantPrivateKey), DEFAULT_CHARSET);
7    } catch(Exception e) {
8        throw new AlipayApiException(e);
9    }
10    return signatureValue;
11}
12
13/**
14 * Generate base64 encoded signature using the sender's private key
15 *
16 * @param reqContent:    the original content to be signed by the sender
17 * @param strPrivateKey: the private key which should be base64 encoded
18 * @return
19 * @throws Exception
20 */
21private static String signWithSHA256RSA(String reqContent, String strPrivateKey) throws Exception {
22    Signature privateSignature = Signature.getInstance(SHA256WITHRSA);
23    privateSignature.initSign(getPrivateKeyFromBase64String(strPrivateKey));
24    privateSignature.update(reqContent.getBytes(DEFAULT_CHARSET));
25    byte[] s = privateSignature.sign();
26
27    return base64Encryptor.encodeToString(s);
28}
29
30/**
31 * URL  encode
32 * @param originalStr
33 * @param characterEncoding
34 * @return
35 * @throws UnsupportedEncodingException
36 */
37private static String encode(String originalStr,
38                             String characterEncoding) throws UnsupportedEncodingException {
39    return URLEncoder.encode(originalStr, characterEncoding);
40}
41
42/**
43 * Generate required headers
44 * @param requestTime
45 * @param clientId
46 * @param keyVersion
47 * @param signatureValue
48 * @return
49 */
50private Map<String,String> buildBaseHeader(String requestTime, String clientId, Integer keyVersion, String signatureValue) {
51    Map<String, String> header = new HashMap<String, String>();
52    header.put("Content-Type", "application/json; charset=UTF-8");
53    header.put("Request-Time", requestTime);
54    header.put("client-id", clientId);
55    if(keyVersion == null) {
56        keyVersion = DEFULT_KEY_VERSION;
57    }
58    String signatureHeader = "algorithm=RSA256,keyVersion=" + keyVersion + ",signature=" + signatureValue;
59    header.put(Signature, signatureHeader);
60    return header;
61}
Handle the payment result
Client-side & Server-side
pay response (Client-side)

When receiving the pay response from Alipay+, handle the payment result according to the value of result.resultStatus:

  • result.resultStatus=S: indicates that the payment was successful. Display the buyer the payment success result.
  • result.resultStatus=F: indicates that the payment failed. Display the buyer the payment failure result.
  • result.resultStatus=U: indicates that the payment is in process. Redirect the buyer to the URL returned by Alipay+.

Handle the redirect URL

When the value of result.resultStatus is U, at least one of the following URLs is returned:

  • normalUrl: The URL of an HTTPS address, used to redirect the buyer to the website page of the payment method on the same browser page of your website. Note that this URL may include a button to invoke the payment method App.
  • schemeUrl: The scheme URL that is used to open a payment method app.
  • applinkUrl: The Android App Link or iOS Universal Link that is used for redirection in the payment process.

Handle the URLs based on different terminal types (Web, WAP, and App) and operating systems (iOS and Android).

Web: The buyer places an order on your PC website.
1if (serverResponse.normalUrl) {
2window.open(serverResponse.normalUrl, '_blank');
3}
WAP: The buyer places an order on your mobile browser website.
1if (serverResponse.applinkUrl) {
2  window.location.href = serverResponse.applinkUrl;
3} else if (serverResponse.normalUrl) {
4  window.location.href = serverResponse.normalUrl;
5} else if (serverResponse.redirectActionForm.redirectUrl) {
6  window.location.href = serverResponse.redirectActionForm.redirectUrl;
7}
App (iOS): The buyer places an order from your App on iOS.
1if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
2    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:Url] options:@{} completionHandler:nil];
3}else{ 
4    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:Url]];
5}
App (Android): The buyer places an order from your App on Android.
1try {
2  Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Url));
3  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
4  // use the startActivity function to redirect to the wallet app 
5  startActivity(intent);
6} catch (Exception e) {
7  e.printStackTrace();
8}
Asynchronous notification (Server-side)

Alipay+ sends you an asynchronous notification when the payment reaches a final status of success or failure. Make sure that paymentNotifyUrl that you provide through the pay API can receive notifications.

When you receive the payment result notification, follow the steps below to handle it:

  1. Verify the notification.
  2. Update your order status.
  3. Send a notification response to Alipay+ following the fixed format shown in the code editor. You do not need to sign the response.
Verifying the notification:
1private boolean checkRspSign(String httpMethod, String path, String clientId, String responseTime, String rspBody, String rspSignValue) throws AlipayApiException {
2    try {
3        String rspContent = httpMethod + " " + path + "\n" + clientId + "." + timeString
4        + "." + content;
5        return verifySignatureWithSHA256RSA(rspContent, decode(signature, DEFAULT_CHARSET), alipayPublicKey);
6    } catch (Exception e) {
7        throw new AlipayApiException(e);
8    }
9
10}
11
12/**
13 * Verify if the received signature is correctly generated with the sender's public key
14 *
15 * @param rspContent: the original content signed by the sender and to be verified by the receiver.
16 * @param signature:  the signature generated by the sender
17 * @param strPk:      the public key string-base64 encoded
18 * @return
19 * @throws Exception
20 */
21private static boolean verifySignatureWithSHA256RSA(String rspContent, String signature, String strPk) throws Exception {
22    PublicKey publicKey = getPublicKeyFromBase64String(strPk);
23
24    Signature publicSignature = Signature.getInstance(SHA256WITHRSA);
25    publicSignature.initVerify(publicKey);
26    publicSignature.update(rspContent.getBytes(DEFAULT_CHARSET));
27
28    byte[] signatureBytes = base64Encryptor.decode(signature);
29    return publicSignature.verify(signatureBytes);
30
31}
32
33/**
34 * URL decode
35 * @param originalStr
36 * @param characterEncoding
37 * @return
38 * @throws UnsupportedEncodingException
39 */
40private static String decode(String originalStr,
41                             String characterEncoding) throws UnsupportedEncodingException {
42    return URLDecoder.decode(originalStr, characterEncoding);
43}
Notification response:
1{
2  "result": {
3    "resultCode": "SUCCESS",
4    "resultStatus": "S",
5    "resultMessage": "Success"
6  }
7}
Handle the capture result notification
Server-side

Alipay+ automatically captures funds for you after the buyer completes the card authorization payment. When the capture reaches a final status of success or failure, Alipay+ sends an asynchronous notification to you. Make sure that paymentNotifyUrl that you provide through the pay API can receive notifications.

When you receive the capture result notification, follow the steps below to handle it:

  1. Verify the notification.
  2. Update your order status.
  3. Send a notification response to Alipay+ following the fixed format shown in the code editor. You do not need to sign the response.
Verifying the notification:
1private boolean checkRspSign(String httpMethod, String path, String clientId, String responseTime, String rspBody, String rspSignValue) throws AlipayApiException {
2    try {
3        String rspContent = httpMethod + " " + path + "\n" + clientId + "." + timeString
4        + "." + content;
5        return verifySignatureWithSHA256RSA(rspContent, decode(signature, DEFAULT_CHARSET), alipayPublicKey);
6    } catch (Exception e) {
7        throw new AlipayApiException(e);
8    }
9
10}
11
12/**
13 * Verify if the received signature is correctly generated with the sender's public key
14 *
15 * @param rspContent: the original content signed by the sender and to be verified by the receiver.
16 * @param signature:  the signature generated by the sender
17 * @param strPk:      the public key string-base64 encoded
18 * @return
19 * @throws Exception
20 */
21private static boolean verifySignatureWithSHA256RSA(String rspContent, String signature, String strPk) throws Exception {
22    PublicKey publicKey = getPublicKeyFromBase64String(strPk);
23
24    Signature publicSignature = Signature.getInstance(SHA256WITHRSA);
25    publicSignature.initVerify(publicKey);
26    publicSignature.update(rspContent.getBytes(DEFAULT_CHARSET));
27
28    byte[] signatureBytes = base64Encryptor.decode(signature);
29    return publicSignature.verify(signatureBytes);
30
31}
32
33/**
34 * URL decode
35 * @param originalStr
36 * @param characterEncoding
37 * @return
38 * @throws UnsupportedEncodingException
39 */
40private static String decode(String originalStr,
41                             String characterEncoding) throws UnsupportedEncodingException {
42    return URLDecoder.decode(originalStr, characterEncoding);
43}
Notification response:
1{
2  "result": {
3    "resultCode": "SUCCESS",
4    "resultStatus": "S",
5    "resultMessage": "Success"
6  }
7}