package com.antom.easysafepay.sdk; import com.alibaba.fastjson.JSON; import com.alipay.global.api.AlipayClient; import com.alipay.global.api.DefaultAlipayClient; import com.alipay.global.api.exception.AlipayApiException; import com.alipay.global.api.model.Result; import com.alipay.global.api.model.ResultStatusType; import com.alipay.global.api.model.ams.*; import com.alipay.global.api.model.constants.EndPointConstants; import com.alipay.global.api.model.constants.ProductSceneConstants; import com.alipay.global.api.request.ams.notify.AlipayAuthNotify; import com.alipay.global.api.request.ams.pay.AlipayPayQueryRequest; import com.alipay.global.api.request.ams.pay.AlipayPaymentSessionRequest; import com.alipay.global.api.response.ams.pay.AlipayPayQueryResponse; import com.alipay.global.api.response.ams.pay.AlipayPaymentSessionResponse; import com.alipay.global.api.tools.WebhookTool; import lombok.Data; import org.joda.money.CurrencyUnit; import org.joda.money.Money; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * sample payment server using Antom SDK integration mode **/ @Controller @CrossOrigin @SpringBootApplication public class PaymentServer { /** * replace with your client id
* find your client id here: quickStart */ public static final String CLIENT_ID = "your_client_id"; /** * replace with your antom public key (used to verify signature)
* find your antom public key here: quickStart */ public static final String ANTOM_PUBLIC_KEY = "antom_public_key"; /** * replace with your private key (used to sign)
* please ensure the secure storage of your private key to prevent leakage */ public static final String MERCHANT_PRIVATE_KEY = "your_private_key"; private final static AlipayClient CLIENT = new DefaultAlipayClient( EndPointConstants.SG, MERCHANT_PRIVATE_KEY, ANTOM_PUBLIC_KEY, CLIENT_ID); // Save the mapping between authState and payment information private static final Map authStatePayment = new HashMap<>(); // Save the mapping between userId and user info private static final Map users = new HashMap<>(); static { users.put("antom-easysafepay",new User("antom-easysafepay","852-91234567")); } public static void main(String[] args) { SpringApplication.run(PaymentServer.class, args); System.out.println("Open your browser and visit: http://localhost:8080"); } @PostMapping("/payment/createSession") public ResponseEntity createPaymentSession(@RequestBody PaymentVO payment) { AlipayPaymentSessionRequest alipayPaymentSessionRequest = new AlipayPaymentSessionRequest(); alipayPaymentSessionRequest.setProductCode(ProductCodeType.AGREEMENT_PAYMENT); alipayPaymentSessionRequest.setProductScene(ProductSceneConstants.EASY_PAY); // replace with your paymentRequestId String paymentRequestId = UUID.randomUUID().toString(); alipayPaymentSessionRequest.setPaymentRequestId(paymentRequestId); // convert amount unit(in practice, amount should be calculated on your serverside) // For details, please refer to: Usage rules of the Amount object long amountMinorLong = Money.of(CurrencyUnit.of(payment.currency), new BigDecimal(payment.amountValue)).getAmountMinorLong(); // set amount Amount amount = Amount.builder().currency(payment.currency).value(String.valueOf(amountMinorLong)).build(); alipayPaymentSessionRequest.setPaymentAmount(amount); // set settlement strategy // replace with your existing settlement currency SettlementStrategy settlementStrategy = SettlementStrategy.builder().settlementCurrency("USD").build(); alipayPaymentSessionRequest.setSettlementStrategy(settlementStrategy); User loginUser = users.get(payment.getUserId()); // set paymentMethod PaymentMethod paymentMethod = PaymentMethod.builder().paymentMethodType(payment.paymentMethodType).build(); if(loginUser.getPaymentMethodTypeAccessToken().containsKey(payment.getPaymentMethodType())){ // user has authorized String accessToken = loginUser.getPaymentMethodTypeAccessToken().get(payment.getPaymentMethodType()); paymentMethod.setPaymentMethodId(accessToken); }else{ // set agreementInfo // replace with your authState String authState = UUID.randomUUID().toString(); // The login ID that the user used to register in the payment method client. The login ID can be the user's email address or phone number. // Specify this parameter to free users from manually entering their login IDs. String userLoginId = loginUser.getPhoneNumber(); AgreementInfo agreementInfo = AgreementInfo.builder().authState(authState).userLoginId(userLoginId).build(); alipayPaymentSessionRequest.setAgreementInfo(agreementInfo); // save the paymentMethodType corresponding to the authState authStatePayment.put(authState, payment); } alipayPaymentSessionRequest.setPaymentMethod(paymentMethod); // set buyer info Buyer buyer = Buyer.builder().referenceBuyerId("yourBuyerId").build(); // replace with your orderId String orderId = UUID.randomUUID().toString(); // set order Info Order order = Order.builder().referenceOrderId(orderId). orderDescription("antom sdk testing order").orderAmount(amount).buyer(buyer).build(); alipayPaymentSessionRequest.setOrder(order); // replace with your notify url // or configure your notify url here: Notification URL alipayPaymentSessionRequest.setPaymentNotifyUrl("http://www.yourNotifyUrl.com/payment/receivePaymentNotify"); // replace with your redirect url alipayPaymentSessionRequest.setPaymentRedirectUrl( "http://localhost:8080/index.html?paymentRequestId=" + paymentRequestId); AlipayPaymentSessionResponse alipayPaymentSessionResponse; try { long startTime = System.currentTimeMillis(); System.out.println("payment request: " + JSON.toJSONString(alipayPaymentSessionRequest)); alipayPaymentSessionResponse = CLIENT.execute(alipayPaymentSessionRequest); System.out.println("payment response: " + JSON.toJSONString(alipayPaymentSessionResponse)); System.out.println("payment request cost time: " + (System.currentTimeMillis() - startTime) + "ms\n"); } catch (AlipayApiException e) { return ResponseEntity.ok().body(new ApiResponse(paymentRequestId, payment.getUserId(), e)); } return ResponseEntity.ok().body(new ApiResponse(paymentRequestId, payment.getUserId(), alipayPaymentSessionResponse)); } @PostMapping("/authorizations/receiveAuthNotify") @ResponseBody public Result receiveAuthNotify(HttpServletRequest request, @RequestBody String notifyBody) { // retrieve the required parameters from http request String requestUri = request.getRequestURI(); String requestMethod = request.getMethod(); // retrieve the required parameters from request header String requestTime = request.getHeader("request-time"); String clientId = request.getHeader("client-id"); String signature = request.getHeader("signature"); try { // verify the signature of notification boolean verifyResult = WebhookTool.checkSignature(requestUri, requestMethod, clientId, requestTime, signature, notifyBody, ANTOM_PUBLIC_KEY); if (!verifyResult) { throw new RuntimeException("Invalid notify signature"); } // deserialize the notification body AlipayAuthNotify authNotify = JSON.parseObject(notifyBody,AlipayAuthNotify.class); if (authNotify != null && "SUCCESS".equals(authNotify.getResult().getResultCode()) && "TOKEN_CREATED".equals(authNotify.getAuthorizationNotifyType())) { // save user's PaymentMethodType corresponding to accessToken PaymentVO payment = authStatePayment.get(authNotify.getAuthState()); User user = users.get(payment.getUserId()); user.getPaymentMethodTypeAccessToken().put(payment.getPaymentMethodType(), authNotify.getAccessToken()); return Result.builder().resultCode("SUCCESS").resultMessage("success.").resultStatus(ResultStatusType.S).build(); } } catch (Exception e) { return Result.builder().resultCode("FAIL").resultMessage("fail.").resultStatus(ResultStatusType.F).build(); } return Result.builder().resultCode("SYSTEM_ERROR").resultMessage("system error.").resultStatus(ResultStatusType.F).build(); } @PostMapping("/payment/inquiryPayment") public ResponseEntity inquiryPayment(@RequestBody Map map) { String paymentRequestId = map.get("paymentRequestId"); AlipayPayQueryRequest alipayPayQueryRequest = new AlipayPayQueryRequest(); alipayPayQueryRequest.setPaymentRequestId(paymentRequestId); AlipayPayQueryResponse alipayPayQueryResponse; try { long startTime = System.currentTimeMillis(); System.out.println("inquiry payment request: " + JSON.toJSONString(alipayPayQueryRequest)); alipayPayQueryResponse = CLIENT.execute(alipayPayQueryRequest); System.out.println("inquiry payment response: " + JSON.toJSONString(alipayPayQueryResponse)); System.out.println("inquiry payment request cost time: " + (System.currentTimeMillis() - startTime) + "ms\n"); } catch (AlipayApiException e) { return ResponseEntity.ok().body(new ApiResponse(paymentRequestId, "", e)); } return ResponseEntity.ok().body(new ApiResponse(paymentRequestId, "", alipayPayQueryResponse)); } @Data private static class User{ private String userId; private String phoneNumber; private Map paymentMethodTypeAccessToken; public User(String userId,String phoneNumber) { this.userId = userId; this.phoneNumber = phoneNumber; this.paymentMethodTypeAccessToken = new HashMap<>(); } } @Data public static class PaymentVO { private String userId; private String amountValue; private String currency; private String paymentMethodType; } @Data private static class ApiResponse { private String status = "success"; private String paymentRequestId; private String userId; private String message; private Object data; public ApiResponse(String paymentRequestId, String userId, Object data) { this.paymentRequestId = paymentRequestId; this.userId = userId; this.data = data; } public ApiResponse(String paymentRequestId, String userId, Exception e) { this.paymentRequestId = paymentRequestId; this.userId = userId; this.status = "error"; this.message = e.getMessage(); } } }