Antom, leading provider of tailored payment solutions

Quickstart

Note: This page has been deprecated and is no longer maintained or updated. Visit https://docs.antom.com/ for the latest content.

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:
text
<dependency>
  <groupId>com.alipay.global.sdk</groupId>
  <artifactId>global-open-sdk-java</artifactId>
  <version>2.0.11</version>
</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:
java
String domain = "DOMAIN"
String merchantPrivateKey = "YOUR PRIVATE KEY";
String alipayPublicKey = "ALIPAY PUBLIC KEY"
AlipayClient defaultAlipayClient = new DefaultAlipayClient(domain, merchantPrivateKey, alipayPublicKey);

AlipayPayRequest alipayPayRequest = new AlipayPayRequest();
alipayPayRequest.setClientId(CLIENT_ID);
alipayPayRequest.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:
java
// set order Info
Order order = new Order();

// replace with your orderId
String orderId = UUID.randomUUID().toString();

order.setReferenceOrderId(orderId);
order.setOrderDescription("Test Order");
order.setOrderAmount(amount);
Buyer buyer = new Buyer();
buyer.setReferenceBuyerId("Your Buyer Id");
order.setBuyer(buyer);
order.setOrderAmount(amount);
alipayPayRequest.setOrder(order);
Environment information:
java
// set env Info
Env env = new Env();
env.setTerminalType("WEB");
env.setClientIp("YOUR CUSTOMER IP");
alipayPayRequest.setEnv(env);
order.setEnv(env);
Payment information:
java
// set amount
Amount amount = new Amount();
amount.setCurrency("BRL");
amount.setValue("4200");
alipayPayRequest.setPaymentAmount(amount);

//set settlement currency
SettlementStrategy settlementStrategy = new SettlementStrategy();
settlementStrategy.setSettlementCurrency("USD");
alipayPayRequest.setSettlementStrategy(settlementStrategy);

// replace with your paymentRequestId
String paymentRequestId = UUID.randomUUID().toString();
alipayPayRequest.setPaymentRequestId(paymentRequestId);

// set paymentMethod
PaymentMethod paymentMethod = new PaymentMethod();
paymentMethod.setPaymentMethodType("GCASH");
alipayPayRequest.setPaymentMethod(paymentMethod);

// set productcode
alipayPayRequest.setProductCode("CASHIER_PAYMENT");
Card information (server-to-server mode):
java
//if merchant collect card info, set card info in this paymentMethodMetaData
Map<String, Object> paymentMethodMetaData = new HashMap<String, Object>();
paymentMethodMetaData.put("cardNo", "0255187751531899");
paymentMethodMetaData.put("cvv", "712");
paymentMethodMetaData.put("expiryMonth", "06");
paymentMethodMetaData.put("expiryYear", "28");
paymentMethodMetaData.put("tokenize", false);
JSONObject cardholderName = new JSONObject();
cardholderName.put("firstName", "Alan");
cardholderName.put("lastName", "Wallex");
paymentMethodMetaData.put("cardholderName", cardholderName);
paymentMethod.setPaymentMethodMetaData(paymentMethodMetaData);
Card authorization (Card payments):
java
// set authorization
paymentFactor.setAuthorization(true);
alipayPayRequest.setPaymentFactor(paymentFactor);
Payment redirect URL:
java
// replace with your redirect url
alipayPayRequest.setPaymentRedirectUrl("http://www.yourRedirectUrl.com");
Payment notification URL:
java
// replace with your notify url
alipayPayRequest.setPaymentNotifyUrl("http://www.yourNotifyUrl.com");
Signing a request:
java
private String genSignValue(
  String httpMethod,
  String path,
  String clientId,
  String requestTime,
  String reqBody
) throws AlipayApiException {
  String signatureValue;
  try {
    String reqContent =
      httpMethod + " " + path + "\n" + clientId + "." + timeString + "." + content;
    signatureValue = encode(signWithSHA256RSA(reqContent, merchantPrivateKey), DEFAULT_CHARSET);
  } catch (Exception e) {
    throw new AlipayApiException(e);
  }
  return signatureValue;
}

/**
 * Generate base64 encoded signature using the sender's private key
 *
 * @param reqContent:    the original content to be signed by the sender
 * @param strPrivateKey: the private key which should be base64 encoded
 * @return
 * @throws Exception
 */
private static String signWithSHA256RSA(String reqContent, String strPrivateKey) throws Exception {
  Signature privateSignature = Signature.getInstance(SHA256WITHRSA);
  privateSignature.initSign(getPrivateKeyFromBase64String(strPrivateKey));
  privateSignature.update(reqContent.getBytes(DEFAULT_CHARSET));
  byte[] s = privateSignature.sign();

  return base64Encryptor.encodeToString(s);
}

/**
 * URL  encode
 * @param originalStr
 * @param characterEncoding
 * @return
 * @throws UnsupportedEncodingException
 */
private static String encode(String originalStr, String characterEncoding)
  throws UnsupportedEncodingException {
  return URLEncoder.encode(originalStr, characterEncoding);
}

/**
 * Generate required headers
 * @param requestTime
 * @param clientId
 * @param keyVersion
 * @param signatureValue
 * @return
 */
private Map<String, String> buildBaseHeader(
  String requestTime,
  String clientId,
  Integer keyVersion,
  String signatureValue
) {
  Map<String, String> header = new HashMap<String, String>();
  header.put("Content-Type", "application/json; charset=UTF-8");
  header.put("Request-Time", requestTime);
  header.put("client-id", clientId);
  if (keyVersion == null) {
    keyVersion = DEFULT_KEY_VERSION;
  }
  String signatureHeader =
    "algorithm=RSA256,keyVersion=" + keyVersion + ",signature=" + signatureValue;
  header.put(Signature, signatureHeader);
  return header;
}
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.
javascript
if (serverResponse.normalUrl) {
  window.open(serverResponse.normalUrl, "_blank");
}
WAP: The buyer places an order on your mobile browser website.
javascript
if (serverResponse.applinkUrl) {
  window.location.href = serverResponse.applinkUrl;
} else if (serverResponse.normalUrl) {
  window.location.href = serverResponse.normalUrl;
} else if (serverResponse.redirectActionForm.redirectUrl) {
  window.location.href = serverResponse.redirectActionForm.redirectUrl;
}
App (iOS): The buyer places an order from your App on iOS.
objectivec
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:Url] options:@{} completionHandler:nil];
}else{ 
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:Url]];
}
App (Android): The buyer places an order from your App on Android.
java
try {
  Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Url));
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  // use the startActivity function to redirect to the wallet app
  startActivity(intent);
} catch (Exception e) {
  e.printStackTrace();
}
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:
java
private boolean checkRspSign(
  String httpMethod,
  String path,
  String clientId,
  String responseTime,
  String rspBody,
  String rspSignValue
) throws AlipayApiException {
  try {
    String rspContent =
      httpMethod + " " + path + "\n" + clientId + "." + timeString + "." + content;
    return verifySignatureWithSHA256RSA(
      rspContent,
      decode(signature, DEFAULT_CHARSET),
      alipayPublicKey
    );
  } catch (Exception e) {
    throw new AlipayApiException(e);
  }
}

/**
 * Verify if the received signature is correctly generated with the sender's public key
 *
 * @param rspContent: the original content signed by the sender and to be verified by the receiver.
 * @param signature:  the signature generated by the sender
 * @param strPk:      the public key string-base64 encoded
 * @return
 * @throws Exception
 */
private static boolean verifySignatureWithSHA256RSA(
  String rspContent,
  String signature,
  String strPk
) throws Exception {
  PublicKey publicKey = getPublicKeyFromBase64String(strPk);

  Signature publicSignature = Signature.getInstance(SHA256WITHRSA);
  publicSignature.initVerify(publicKey);
  publicSignature.update(rspContent.getBytes(DEFAULT_CHARSET));

  byte[] signatureBytes = base64Encryptor.decode(signature);
  return publicSignature.verify(signatureBytes);
}

/**
 * URL decode
 * @param originalStr
 * @param characterEncoding
 * @return
 * @throws UnsupportedEncodingException
 */
private static String decode(String originalStr, String characterEncoding)
  throws UnsupportedEncodingException {
  return URLDecoder.decode(originalStr, characterEncoding);
}
Notification response:
json
{
  "result": {
    "resultCode": "SUCCESS",
    "resultStatus": "S",
    "resultMessage": "Success"
  }
}
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:
java
private boolean checkRspSign(
  String httpMethod,
  String path,
  String clientId,
  String responseTime,
  String rspBody,
  String rspSignValue
) throws AlipayApiException {
  try {
    String rspContent =
      httpMethod + " " + path + "\n" + clientId + "." + timeString + "." + content;
    return verifySignatureWithSHA256RSA(
      rspContent,
      decode(signature, DEFAULT_CHARSET),
      alipayPublicKey
    );
  } catch (Exception e) {
    throw new AlipayApiException(e);
  }
}

/**
 * Verify if the received signature is correctly generated with the sender's public key
 *
 * @param rspContent: the original content signed by the sender and to be verified by the receiver.
 * @param signature:  the signature generated by the sender
 * @param strPk:      the public key string-base64 encoded
 * @return
 * @throws Exception
 */
private static boolean verifySignatureWithSHA256RSA(
  String rspContent,
  String signature,
  String strPk
) throws Exception {
  PublicKey publicKey = getPublicKeyFromBase64String(strPk);

  Signature publicSignature = Signature.getInstance(SHA256WITHRSA);
  publicSignature.initVerify(publicKey);
  publicSignature.update(rspContent.getBytes(DEFAULT_CHARSET));

  byte[] signatureBytes = base64Encryptor.decode(signature);
  return publicSignature.verify(signatureBytes);
}

/**
 * URL decode
 * @param originalStr
 * @param characterEncoding
 * @return
 * @throws UnsupportedEncodingException
 */
private static String decode(String originalStr, String characterEncoding)
  throws UnsupportedEncodingException {
  return URLDecoder.decode(originalStr, characterEncoding);
}
Notification response:
json
{
  "result": {
    "resultCode": "SUCCESS",
    "resultStatus": "S",
    "resultMessage": "Success"
  }
}