Accept Apple Pay with UI components
Use Unzer UI component to add Apple Pay payment to your checkout page.
Overview
Using UI components for Apple Pay you create a payment type resource that will be used to make the payment. You need to create an Apple Pay button for this payment method.
Before you begin
Before you begin- Check the basic integration requirements.
- Familiarize yourself with general guide on integrating using UI components.
- See the list of prerequisites for Accepting Apple Pay Payments through the Unzer payment system here: Apple Pay Prerequisites
Using Apple Pay
Apple Pay guidelines
Before you can use Apple Pay as a payment method, you must make sure that your website or app comply with all of the guidelines specified by Apple.
Apple Pay version compatibility
You can accept payments using Apple Pay with the Unzer API. Our code examples use version 6 to provide a good mix of compatibility with most of the Apple devices and the data which you can request from a customer to process orders.
Apple Pay - Good to know
Here are some things that you should keep in mind when implementing Apple Pay in your application:
- The
domainName
parameter from the merchant validation step must be the same as validated for the Apple developer account. - Apple Pay is only available on supported Apple devices. See the full list of supported devices here: Supported devices
Step 1: Add UI components to your payment page client side
Step 1: Add UI components to your payment page [client side] First, you need to initiate our UI components library and add the payment form to your payment page.
Initiate UI component
Initiate UI componentLoad our JS script and CSS stylesheet
Include Unzer’s script and stylesheet on your website.
Always load the script and stylesheet directly from Unzer:
<link rel="stylesheet" href="https://static.unzer.com/v1/unzer.css" />
<script type="text/javascript" src="https://static.unzer.com/v1/unzer.js"></script>
To make your website load faster, insert JavaScript scripts at the bottom of your HTML document.
To minimize the risk of Unzer styles affecting the styles of your webpage, we suggest putting unzer.css on top of other imported CSS files.
Create an Unzer instance
Create an unzer
instance with your public key:
// Creating an unzer instance with your public key
var unzerInstance = new unzer('s-pub-xxxxxxxxxx');
In the previous example, we used a placeholder API key for example purposes. You should replace it with your public key.
Localization and languages
We support localization with locale option parameters. Check the Localization page for a list of all the supported locales.
The auto option (applied by default) uses the client’s browser language.
Here you can see how to set the language, in our case ‘de-DE’ - to do so, add a comma separated parameter to your unzer
instance:
// Creating an unzer instance with your public key
var unzerInstance = new unzer('s-pub-xxxxxxxxxx', {locale: 'de-DE'});
Step 2: Add Apple Pay to your project
Step 2: Add Apple Pay to your projectCreate Apple Pay Button client side
Place the Apple Pay button with this code in the desired place on the page.
<div class="apple-pay-button apple-pay-button-black" lang="us" onclick="yourOnClickHandlerMethod()" title="Start Apple Pay" role="link" tabindex="0"></div>
To learn more about the other options for the available button display, see Apple Pay Documentation.
Create an Apple Pay Session client side
First you need to set-up an ApplePayPaymentRequest
which is then used to create an Apple Pay session. For more information, see Apple Pay documentation.
In this example, we define the function startApplePaySession
that can be called when the pay button is clicked.
function startApplePaySession() {
let applePayPaymentRequest = {
countryCode: 'DE',
currencyCode: 'EUR',
supportedNetworks: ['visa', 'masterCard'],
merchantCapabilities: ['supports3DS'],
total: { label: 'Unzer GmbH', amount: '12.99' },
lineItems: [
{
"label": "Subtotal",
"type": "final",
"amount": "10.00"
},
{
"label": "Free Shipping",
"amount": "0.00",
"type": "final"
},
{
"label": "Estimated Tax",
"amount": "2.99",
"type": "final"
}
]
};
// We adhere to Apple Pay version 6 to handle the payment request.
let session = new ApplePaySession(6, applePayPaymentRequest);
session.onvalidatemerchant = function (event) {
// Call the merchant validation in your server-side integration
}
session.onpaymentauthorized = function (event) {
// The event will contain the data you need to pass to our server-side integration to actually charge the customers card
let paymentData = event.payment.token.paymentData;
// event.payment also contains contact information if needed.
// Create the payment method instance at Unzer with your public key
unzerApplePayInstance.createResource(paymentData)
.then(function (createdResource) {
// Hand over the payment type ID (createdResource.id) to your backend.
})
.catch(function (error) {
// Handle the error. E.g. show error.message in the frontend.
abortPaymentSession(session);
})
}
// Add additional event handler functions ...
session.begin();
}
The Apple Pay session provides various event handlers to define the behaviour of your checkout. Most relevant for payment integration with Unzer are the onvalidatemerchant
and onpaymentauthorized
events. Refer to Apple Developer Documentation to get more information about available event handlers.
Event handler | Description |
---|---|
onvalidatemerchant |
Use this event handler to call your server-side validation endpoint, passing the validationURL from the event object.To complete the validation process, you need to call the session.completeMerchantValidation(merchantSession) , where merchantSession is the object fetched from your server-side integration.Also see Apple Pay Developer documentation |
onpaymentauthorized |
This event is called when the customer authorized the payment via Touch ID, Face ID or passcode. Here you need to create the Unzer payment type resource. You can do this by calling unzerApplePayInstance.createResource(paymentData) , where paymentData is read from the encrypted Apple Pay token in the event parameter.Then you will need to call the backend authorized endpoint in your server-side integration, passing the ID of created payment type resource. To complete the authorization process, you need to call session.completePayment passing either STATUS_SUCCESS or STATUS_FAILURE . |
After this, create an event handler for the OnClick
-function for the Apple Pay button which is defined above.
Inside the event handler function you need to start the Apple Pay session as described previously. for example,
startApplePaySession();
This constructs the ApplePaySession
object and start the session.
Provide Merchant Validation server side
To accept payments via Apple Pay, should be able to process the Apple Pay merchant validation. With this, Apple adds a security layer so that the customer is sure that the merchant and the shop on which they are buying are the same as they expect.
This is a synchronous call from the ApplePaySession
inside the Safari-browser to your backend. For security reasons, the actual call to the Apple Pay server for the validation must be done from your server-side integration. You can create the call to your merchant validation server-side integration through the onvalidatemerchant
event handler. For more details on merchant validation, see Apple Developer Documentation.
The Unzer SDKs also provide an adapter function to process the merchant validation for you.
To construct an ApplepaySession
object, the following parameters are needed:
Parameter | Description |
---|---|
merchantIdentifier |
This can be found in the Apple Developer account. |
displayName |
The merchant name (can be anything). |
domainName |
The domain name which has been validated in the Apple Developer account. |
$applepaySession = new ApplepaySession('your.merchantIdentifier', 'your.merchantName', 'your.domainName');
$appleAdapter = new ApplepayAdapter();
$appleAdapter->init('/path/to/merchant_id.pem', '/path/to/rsakey.key')
// Get the merchant validation url from the frontend.
$merchantValidationURL = urldecode($_POST['merchantValidationUrl']);
try {
$validationResponse = $appleAdapter->validateApplePayMerchant(
$merchantValidationURL,
$applepaySession
);
print_r($validationResponse);
} catch (\Exception $e) {
...
}
String merchantValidationUrl = getMerchantValidationUrlFromFrontend();
ApplePaySession applePaySession = new ApplePaySession(applePayMerchantIdentifier, applePayDisplayName, domainName);
KeyManagerFactory kmf = getKeyManagerFactory();
TrustManagerFactory tmf = getTrustManagerFactory();
String response = ApplePayAdapterUtil.validateApplePayMerchant(merchantValidationUrl, applePaySession, kmf, tmf);
return response;
//TruststoreManagerFactory creation
private TrustManagerFactory getTrustManagerFactory() {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream is = new ClassPathResource("path/to/file").getInputStream();
trustStore.load(is, "password".toCharArray());
is.close();
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(trustStore);
return trustManagerFactory;
}
//KeyManagerFactory creation
private KeyManagerFactory getKeyManagerFactory() {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream is = new ClassPathResource("path/to/file").getInputStream();
keyStore.load(is, "password".toCharArray());
is.close();
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, "password".toCharArray());
return keyManagerFactory;
}
All of the SDKs require the Apple Pay Merchant ID Certificate
to be present and provided to the adapter-function. For more details on how to request an Apple Pay Merchant ID Certificate
, see Apple Developer Documentation.
In the Java SDK you also need to provide the Apple Pay certificate keychain in a trust tore.
Provide a Payment Authorized Endpoint server side
After the customer has authorized the payment via the Apple Pay overlay (Face ID, Touch ID or device passcode), Safari will return an object (encrypted Apple Pay token) with data which you need to create the Apple Pay payment type on the Unzer API. The Unzer payment type will be needed to perform the actual transaction. For this you should provide a backend controller to accept the typeId
from your frontend. This controller returns the result of the API authorization because Apple Pay uses this to display the result to the customer.
As an example you can have a look at this RequestMapping
:
$jsonData = json_decode(file_get_contents('php://input'), false);
$typeId = $jsonData->typeId;
// Catch API errors, write the message to your log and show the ClientMessage to the client.
$response = ['transactionStatus' => 'error'];
try {
// Create an Unzer object using your private key and register a debug handler if you want to.
$unzer = new Unzer('s-priv-xxxxxxxxxxxxxx');
// -> Here you can place the Charge or Authorize call as shown in Step 3 <-
// E.g $transaction = $unzer->performCharge(...);
// Or $transaction = $unzer->performAuthorize(...);
$response['transactionStatus'] = 'pending';
if ($transaction->isSuccess()) {
$response['transactionStatus'] = 'success';
}
} catch (UnzerApiException $e) {
$merchantMessage = $e->getMerchantMessage();
$clientMessage = $e->getClientMessage();
} catch (RuntimeException $e) {
$merchantMessage = $e->getMessage();
}
echo json_encode($response);
String paymentTypeId = getApplePayPaymentTypeIdFromFrontend();
// Create an Unzer object using HttpClientBasedRestCommunication and your private key
Unzer unzer = new Unzer(new HttpClientBasedRestCommunication(), privateKey);
boolean authStatus = false;
Applepay applepay = unzer.fetchPaymentType(paymentTypeId);
try {
// -> Here you can place the Charge or Authorize call as shown in Step 3 <-
// E.g Charge charge = unzer.charge(...);
// Or Authorize authorize = unzer.authorize(...);
// Set the authStatus based on the resulting Status of the Payment-Transaction
// The Functions charge.getStatus() or authorize.getStatus() will return the Status-Enum (SUCCESS, PENDING, ERROR)
if(charge.getStatus().equals(AbstractTransaction.Status.SUCCESS))
{
authStatus = true;
}
} catch (Exception ex) {
log.error(ex.getMessage());
}
return authStatus;
Step 3: Make a payment server side
Make a charge transaction
Make a charge
or authorize
transaction with the Applepay
resource that you created earlier. With a successful charge
transaction, money is transferred from the customer to the merchant and a payment
resource is created. In case of the authorize
transaction, it can be charged after the authorization is successful.
POST https://dev-api.unzer.com/v1/payments/charges
Body:
{
"amount" : "49.99",
"currency" : "EUR",
"returnUrl": "http://example.org",
"resources" : {
"typeId" : "s-apl-xxxxxxxxxxxx"
}
}
$unzer = new Unzer('s-priv-xxxxxxxxxx');
$applePay = $unzer->fetchPaymentType('s-apl-xxxxxxxxxxx');
$charge = $applePay->charge(49.99, 'EUR', 'https://www.my-shop-url.de/returnhandler');
Unzer unzer = new Unzer("s-priv-xxxxxxxxxx");
Charge charge = unzer.charge(BigDecimal.valueOf(49.99), Currency.getInstance("EUR"), "s-apl-wqmqea8qkpqy", new URL("https://www.my-shop-url.de/returnhandler"));
The response looks similar to the following example:
{
"id": "s-chg-1",
"isSuccess": true,
"isPending": false,
"isError": false,
"redirectUrl": "",
"message": {
"code": "COR.000.100.112",
"merchant": "Request successfully processed in 'Merchant in Connector Test Mode'",
"customer": "Your payments have been successfully processed in sandbox mode."
},
"amount": "49.9900",
"currency": "EUR",
"returnUrl": "http://example.org",
"date": "2021-05-14 16:01:24",
"resources": {
"paymentId": "s-pay-xxxxxxx",
"traceId": "c6dc23c6fe91a3e1129da83ebd29deb0",
"typeId": "s-apl-xxxxxxxxxxxx"
},
"paymentReference": "",
"processing": {
"uniqueId": "31HA07BC810C911B825D119A51F5A57C",
"shortId": "4849.3448.4721",
"traceId": "c6dc23c6fe91a3e1129da83ebd29deb0"
}
}
Step 4: Check status of the payment server side
Step 3: Check status of the payment [server side] Once the customer is redirected to the returnUrl
, you can fetch the payment
details from the API, by using the resources.paymentId
from the charge
response above to handle the payment
according to its status. If the status of the payment
is completed
, the payment process has been finished successfully and can be considered as paid. Check all possible payment states here.
GET https://api.unzer.com/v1/payments/{payment_ID}
{
"id": "s-pay-222305",
"state": {
"id": 1,
"name": "completed"
},
"amount": {
"total": "49.9900",
"charged": "49.9900",
"canceled": "0.0000",
"remaining": "0.0000"
},
"currency": "EUR",
"orderId": "",
"invoiceId": "",
"resources": {
"customerId": "",
"paymentId": "s-pay-222305",
"basketId": "",
"metadataId": "",
"payPageId": "",
"traceId": "70ddf3152a798c554d9751a6d77812ae",
"typeId": "s-apl-wqmqea8qkpqy"
},
"transactions": [
{
"date": "2021-05-10 00:51:03",
"type": "charge",
"status": "success",
"url": "https://api.unzer.com/v1/payments/s-pay-222305/charges/s-chg-1",
"amount": "49.9900"
}
]
}
Step 5: Display the payment result client side
Step 4: Display the payment result [client side] Use the information from the Check status of the payment step to display the payment result to your customer.
This can be the success or error page of your shop. If something went wrong, you can use the client message from the API response and show it to the customer.
Manage payment server side
For more details on managing Apple Pay payments, such as refunding them, see Manage Apple Pay payments.
Notifications
NotificationsWe recommend subscribing to the payment
event to receive notifications about any changes to the payment
resource. As soon as the event is triggered you should fetch the payment
and update the order status in your shop according to its status.
{
"event":"payment.pending",
"publicKey":"s-pub-xxxxxxxxxx",
"retrieveUrl":"https://api.unzer.com/v1/payments/s-pay-774",
"paymentId":"s-pay-774"
}
For more details on implementing webhooks
to receive notifications, see Notifications page.
Error handling
Error handlingAll requests to the API can result in an error that should be handled. Refer to the Error handling guide to learn more about Unzer API (and other) errors and handling them.
Test & go live
Test & go liveYou should always test your integration before going live. First perform test transactions using test data. Next, check against Integration checklist and Go-live checklist to make sure the integration is complete and you’re ready to go live.