Integrating Apple Pay in Spring Boot projects requires the following steps:
- Configure Apple Developer Account: Create a merchant ID in the Apple Developer Center and generate a related payment processing certificate.
-
Configure HTTPS: Apple Pay requires that the server must use the HTTPS protocol. You can use the JDK's own
keytool
The tool generates a self-signed certificate, or obtains a certificate from a trusted certificate authority. -
Integrated Payment SDK: In Spring Boot projects, you can use third-party payment integration libraries, such as
pay-spring-boot-starter
, to simplify the implementation of the payment process.
Here is an example of a Spring Boot-based scenario that shows how to integrate Apple Pay and process payment callbacks:
1. Configure Apple Pay related parameters
existAdd relevant configurations for Apple Pay in:
applepay: merchantId: your_merchant_id merchantCertificatePath: path_to_your_merchant_certificate.p12 merchantCertificatePassword: your_certificate_password merchantIdentifier: your_merchant_identifier
2. Create a payment service category
Create a service classApplePayService
, used to process payment requests and verify payment results:
@Service public class ApplePayService { @Value("${}") private String merchantId; @Value("${}") private String merchantCertificatePath; @Value("${}") private String merchantCertificatePassword; @Value("${}") private String merchantIdentifier; public String createPaymentSession(String validationUrl) { // Load the merchant certificate KeyStore keyStore = ("PKCS12"); try (InputStream keyInput = new FileInputStream(merchantCertificatePath)) { (keyInput, ()); } // Create SSL context KeyManagerFactory kmf = (()); (keyStore, ()); SSLContext sslContext = ("TLS"); ((), null, null); // Set up HTTPS connection URL url = new URL(validationUrl); HttpsURLConnection connection = (HttpsURLConnection) (); (()); ("POST"); ("Content-Type", "application/json"); // Build request data JSONObject requestData = new JSONObject(); ("merchantIdentifier", merchantIdentifier); ("displayName", "Your Store Name"); ("initiative", "web"); ("initiativeContext", ""); // Send a request (true); try (OutputStream os = ()) { (().getBytes(StandardCharsets.UTF_8)); } // Read the response try (InputStream is = (); BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { StringBuilder response = new StringBuilder(); String line; while ((line = ()) != null) { (line); } return (); } } public boolean validatePayment(String paymentData) { // Apple Verify the URL of the server String url = "/verifyReceipt"; // Sandbox environment // String url = "/verifyReceipt"; // Production environment try { // Build the JSON data for verification requests JSONObject requestJson = new JSONObject(); ("receipt-data", paymentData); // If the subscription is automatically renewed, the following fields need to be added // ("password", "your_shared_secret"); // Create HTTP connection URL verifyUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) (); ("POST"); ("Content-Type", "application/json"); (true); // Send request data try (OutputStream os = ()) { (().getBytes(StandardCharsets.UTF_8)); } // Read response data int responseCode = (); if (responseCode == 200) { try (InputStream is = (); BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { StringBuilder response = new StringBuilder(); String line; while ((line = ()) != null) { (line); } // parse response JSON JSONObject responseJson = new JSONObject(()); int status = ("status"); //Judge payment results based on the status field if (status == 0) { // Verification is successful, payment is valid return true; } else if (status == 21007) { // The receipt is a sandbox environment, but sent to the verification server in the production environment // Need to resend to the sandbox environment for verification // Here you can call the validatePayment method recursively and use the URL of the sandbox environment // Be careful to avoid recursion traps and ensure that infinite recursion is not return validatePaymentInSandbox(paymentData); } else { // Verification failed, payment is invalid return false; } } } else { // The HTTP response code is not 200, indicating that the request failed return false; } } catch (Exception e) { (); return false; } } }
3. Create a payment controller
Create a controllerApplePayController
, used to handle payment requests and callbacks on the front end:
@RestController @RequestMapping("/applepay") public class ApplePayController { @Autowired private ApplePayService applePayService; @PostMapping("/payment-session") public ResponseEntity<String> createPaymentSession(@RequestBody Map<String, String> request) { String validationUrl = ("validationUrl"); String paymentSession = (validationUrl); return (paymentSession); } @PostMapping("/payment-result") public ResponseEntity<String> handlePaymentResult(@RequestBody Map<String, Object> paymentResult) { String paymentData = (String) ("paymentData"); boolean isValid = (paymentData); if (isValid) { // The logic of processing payment success return ("Payment successful"); } else { // Logic of processing payment failure return (HttpStatus.BAD_REQUEST).body("Payment validation failed"); } } }
4. Front-end integration of Apple Pay
In the front-end page, use the JavaScript library provided by Apple to handle the payment process of Apple Pay:
<script type="text/javascript"> ('DOMContentLoaded', function() { if ( && ()) { var applePayButton = ('apple-pay-button'); = 'block'; ('click', function() { var paymentRequest = { countryCode: 'US', currencyCode: 'USD', total: { label: 'Your Store Name', amount: '10.00' }, supportedNetworks: ['visa', 'masterCard', 'amex'], merchantCapabilities: ['supports3DS'] }; var session = new ApplePaySession(3, paymentRequest); = function(event) { fetch('/applepay/payment-session', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: ({ validationUrl: }) }) .then(function(response) { return (); }) .then(function(merchantSession) { (merchantSession); }); }; = function(event) { var paymentData = ; fetch('/applepay/payment-result', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: ({ paymentData: paymentData }) }) .then(function(response) { if () { (ApplePaySession.STATUS_SUCCESS); } else { (ApplePaySession.STATUS_FAILURE); } }); }; ();
This is the end of this article about using SpringBoot to simply implement an Apple payment scenario. For more related SpringBoot Apple payment content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!