Accept Apple Pay with UI components
Overview
Use Unzer UI v2 component to add Unzer Apple Pay payment to your checkout page.
- See the list of prerequisites for Accepting Apple Pay Payments through the Unzer payment system here: Apple Pay Prerequisites
Legacy integration
This page describes the most recent integration of the UI Components, introduced in Jan 2025. For the Legacy integration guide go here.
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
Before you begin
Before you begin- Check the basic integration requirements.
- Familiarize yourself with general guide on integrating using UI components.
Step 1: Add UI components v2 to your payment pageclient side
Step 1: Add UI components v2 to your payment page [client side]First, you need to initiate our UI components v2 library and add the needed payment type component to your payment page.
Initiate UI Components
Initiate UI Components v2Load the Unzer JS script
Load the Unzer JS scriptInclude the Unzer JS script on your website. This will load all the Unzer custom UI components with unzer-
prefixed. For example, <unzer-paylater-invoice>
.
Make sure to always include the script directly from the Unzer domain https://static-v2.unzer.com
.
<script
type="module"
src="https://static-v2.unzer.com/v2/ui-components/index.js"
></script>
To make your website load faster, import the unzer script at the bottom of your HTML document.
Make sure to import the script as type=“module”.
To learn which URLs must be added to the allowlist for Unzer UI components in your content security policy, please refer to Content security policy section.
It is a good practice to put your website in loading state until the Unzer script is loaded, and the UI components are ready to use.
// Make sure initially your application is in loading state
// until all Unzer components are loaded
Promise.all([
customElements.whenDefined("unzer-payment"),
// Probably add any other Unzer components used here. For example:
// customElements.whenDefined("unzer-paylater-invoice"),
]).then(() => {
// Hide the loading state and proceed with next steps
}).catch((error) => {
// Handle any error that might occur during the
// loading process and initialization
});
UI setup and configuration
UI setup and configurationTo securely collect payment data from your customer, you need to add the <unzer-payment>
component, inside which you insert the needed payment type components.
<unzer-checkout>
element.
This will provide automatic handling for enabling/disabling the submit button depending on the current status,
and showing/hiding of brand icons.<unzer-payment
id="unzer-payment"
publicKey="s-pub-xyz"
locale="de-DE">
<!-- ... Here you will need to add the Unzer payment type tag, so the form UI elements will be inserted -->
<!-- e.g <unzer-paylater-invoice></unzer-paylater-invoice> -->
</unzer-payment>
<unzer-checkout id='unzer-checkout'>
<button type="submit" id="yourPaymentButtonId">Pay</button>
</unzer-checkout>
Following parameters need to be passed.
Parameter | Type | Description | Default value |
---|---|---|---|
publicKey (required) | String | The merchant public key. | - |
locale | String | The used locale. For more information on supported locales, see Localization. | Browser user defined locale. |
initData | object | A key/value object in JSON-format containing data to initialize the payment type. For more information, Check payment methods and their features. | Empty object {} |
Optional: Customize UI components
Optional: Customize UI componentsOur UI components v2 are provided with a default theme that contains base styles. You can easily customize these styles by overriding the following CSS variables.
Variable name | Description | Affected components |
---|---|---|
--unzer-font | Replaces all fonts with the given font. Users can define any font-face and provide the name of the custom font-face. | typography |
--unzer-text-color | The font color use for typography. | typography, icons |
--unzer-brand-color | The main color of the application. | button, checkbox, radio, loader |
--unzer-background-color | The page background. | |
--unzer-link-color | The color of links. | link |
--unzer-corner-radius | Whether controls will have rounded corners or not. Values can be either 0 or 1. | button, tags, chips |
--unzer-shadows | Whether shadows are enabled or not. Values can be either 0 or 1. | button, card |
<head>
<style>
:root {
--unzer-font: SFMono;
--unzer-brand-color: #ee1818;
--unzer-text-color: #f19316;
--unzer-background-color: #6a9472;
--unzer-link-color: #1330ef;
--unzer-corner-radius: 0;
--unzer-shadows: 1
}
</style>
</head>
Step 2: Add Apple Pay to your project
First you need to insert the Unzer Apple Pay element <unzer-apple-pay>
inside the <unzer-payment>
.
<unzer-payment
id="unzer-payment"
publicKey="s-pub-xyz"
locale="de-DE">
<unzer-apple-pay></unzer-apple-pay>
</unzer-payment>
<unzer-checkout id='unzer-checkout'></unzer-checkout>
In case you want also to create/update your customer information, then you will need to use our Unzer UI customer elements.
Option 1: Implement with customer elements
Option 1: Implement with customer elementsIf you don’t have information about the customer (and the corresponding customerID) or want to update information of an already existing customer, you can do so using Unzer UI customer elements.
Customer element | Description |
---|---|
<unzer-shipping-address> | Adds the customer shipping address information (email, salutation, firstname, lastname, country, street, post code, city, mobile number). |
<unzer-billing-address> | Adds the customer billing address information (firstname, lastname, country, street, post code, city). |
The Unzer UI customer elements can be inserted either inside or outside the <unzer-payment>
element.
On submit, all data from the added Unzer UI customer elements will be gathered and submitted together with the payment form,
in order to create the customer and payment type resources.
In case you wish to initialize the customer elements with the data of an already created customer, you will need to call
the setCustomerData()
function of the <unzer-payment>
element, and pass a customer object in JSON format.
customer object
Parameter | Type | Description | Default value |
---|---|---|---|
id | String | The ID of the customer you wish to update. If not passed, then a new customer will be created. | |
salutation | String | The salutation for the customer. Allowed values are:"mr" , "mrs" , "diverse" . | "mr" |
firstname | String | The first name of the customer. | "" |
lastname | String | The last name of the customer. | "" |
birthDate | String | The birth date of the customer. | "" |
email | String | The E-mail of the customer. | "" |
mobileNumber | mobileNumber Object | The mobile number. | {} |
shippingAddress | address object | The shipping address for the customer in JSON format. | {} |
billingAddress | address object | The billing address for the customer in JSON format. | {} |
address object
Parameter | Type | Description | Default value |
---|---|---|---|
name | String | The firstname + lastname of the customer. | "" |
street | String | The street and house number. | "" |
zip | String | The zip-code. | "" |
city | String | The city. | "" |
state | String | The state. | "" |
country | String | The country ISO country code ISO 3166 ALPHA-2. | "DE" |
shippingType only in shippingAddress | String | The shippingType. Allowed values are:"equals-billing" , "different-address" , "branch-pickup" , "post-office-pickup" , "pack-station" . | "DE" |
mobileNumber object
Parameter | Type | Description | Default value |
---|---|---|---|
prefix | String | The country prefix of the mobile number. | "" |
phone | String | The mobile number. | "" |
The following code example shows the options described above:
<unzer-payment
id="unzer-payment"
publicKey="s-pub-xyz"
locale="de-DE">
<unzer-apple-pay></unzer-apple-pay>
</unzer-payment>
<p>Shipping Information</p>
<unzer-personal-info></unzer-personal-info>
<unzer-shipping-address></unzer-shipping-address>
<p>Billing Information</p>
<unzer-billing-address></unzer-billing-address>
<unzer-checkout id='unzer-checkout'></unzer-checkout>
const unzerPaymentElement = document.getElementById('unzer-payment');
unzerPaymentElement.setCustomerData({
"id": "s-cst-xyz",
"lastname": "Universum",
"firstname": "Peter",
"salutation": "mr",
"birthDate": "20.12.1987",
"mobileNumber": {
"prefix": "49",
"phone": "1234"
},
"shippingAddress": {
"name": "Peter Universum",
"street": "Hugo-Junkers-Str. 5",
"zip": "60386",
"city": "Frankfurt am Main",
"country": "DE",
"shippingType": "equals-billing"
},
"billingAddress": {
"state": "Peter Universum",
"street": "Hugo-Junkers-Str. 5",
"zip": "60386",
"city": "Frankfurt am Main",
"country": "DE"
}
})
Option 2: Create the customer on the server side
You can also use the customer data provided by your shop system to create the customer
resource on the server side.
This way you can omit rendering the customer form in the front end and just create the resource and use the ID in
your transaction request.
In that case you just need to render the payment type form and create a simple HTML button on the client side.
Create an Apple Pay payment requestclient side
First you need to set-up an ApplePayPaymentRequest. For more information, see Apple Pay Demo - Create a Payment Request.
const 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"
}
],
onPaymentAuthorizedCallback: async () => {}
};
The created payment request can then be used to create the ApplePaySession.
Start the Apple Pay sessionclient side
By calling the setApplePayData
method with the valid session object containing all required information you created above, the Apple Pay session will be started. After the session is started, the browser invokes the onvalidatemerchant handler, which will fetch a merchant session from the server, and the merchant validation process is started. The browser then displays the payment sheet.
// This will provide a default onvalidatemerchant implementation
unzerPaymentElement.setApplePayData(paymentDataRequestObject);
<unzer-payment
id="unzer-payment"
publicKey="s-pub-xyz"
locale="de-DE"
>
<unzer-apple-pay></unzer-apple-pay>
</unzer-payment>
const paymentDataRequestObject = {applePayData: applePayPaymentRequest}
const unzerPaymentElement = document.getElementById('unzer-payment');
unzerPaymentElement.setApplePayData(paymentDataRequestObject);
Authorize the payment and create payment type resource
After the customer authenticates the payment via Touch ID, Face ID or passcode, the onpaymentauthorized
is called with the Apple pay encrypted token.
Event handler | Description |
---|---|
onpaymentauthorized (required) | This callback is called when the payment is authorized. Here you need to create the Unzer payment type resource. You can do this by calling unzerPaymentElement.submit .To complete the authorization process, you need to return submitResponse to confirm successful authorization. See Full example below. |
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8" />
<title>Apple Pay Payment</title>
<script>
Promise.all([
customElements.whenDefined("unzer-payment"),
]).then(() => {
const unzerPaymentElement = document.getElementById('unzer-payment');
const 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"
}
],
onPaymentAuthorizedCallback: async () => {
return await unzerPaymentElement?.submit().then(
(result) => result.submitResponse,
);
},
};
unzerPaymentElement.setApplePayData({applePayData: applePayPaymentRequest});
}).catch((error) => {
// Handle any error that might occur during the
// loading process and initialization
});
</script>
<script
type="module"
src="https://static-v2.unzer.com/v2/ui-components/index.js"
></script>
</head>
<body>
<unzer-payment
id="unzer-payment"
publicKey="{{PUBLIC_KEY}}"
locale="de-DE"
>
<unzer-apple-pay></unzer-apple-pay>
</unzer-payment>
<unzer-checkout id='unzer-checkout'></unzer-checkout>
</body>
</html>
Express Checkoutclient side
You can integrate Apple Pay as express checkout utilizing Apple Pay JS API. It allows you to collect address data from the customer and to update costs based on selected shipping methods. You can find examples of how to collect the customer’s address data and update costs based on the shipping method below.
To access the created Apple Pay session, you can add the initApplePaySession
callback to your applePayPaymentRequest
. This callback allows you to interact with the Apple Pay session when it’s initialized.
// ... For previously created applePayPaymentRequest object.
// Additionally add the initApplePaySession callback.
applePayPaymentRequest.initApplePaySession = (applePaySession) => {
const session = applePaySession;
},
There are other event handlers that you might need to implement to customize the checkout experience we are not covering in our documentation. Please refer to the Apple Pay documentation ApplePayPaymentRequest page.
For more information about the ApplePaySession object and events you can react on, see the Apple Pay documentation ApplePaySession page.
Collect Customer Address data
To collect the customer address data, you can set the requiredShippingContactFields
and requiredBillingContactFields
properties when creating the ApplePayPaymentRequest
object.
That way you can get the Address data from the onpaymentauthorized
event handler after the authorization of the
payment.
Add these properties to your ApplePayPaymentRequest
object as described in section Create an Apple Pay payment request and Session.
let applePayPaymentRequest = {
// ... previously set properties.
// Set the requiredShippingContactFields and requiredBillingContactFields properties
requiredShippingContactFields: ['postalAddress', 'name', 'email', 'phone'],
requiredBillingContactFields: ['postalAddress', 'name', 'email', 'phone'],
};
onpaymentauthorized
event handler, you can get the shippingContact
and billingContact
properties from
the payment
object to store the customer address data for your order.// ... previously created session object (ApplePaySession).
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;
let shippingContact = event.payment.shippingContact; // Store the shipping contact data for express checkout
let billingContact = event.payment.billingContact; // Store the billing contact data for express checkout
// Process the payment...
}
// Add additional event handler functions ...
Update costs based or shipping methods
You can update the costs based on the customer’s shipping method.
You need to provide available shipping methods and the total cost for each shipping method in the shippingMethods
property of the ApplePayPaymentRequest
object.
To update the costs based on the customer’s shipping method, you can use the shippingMethodSelected
event handler.
This event is called when the customer selects a shipping method.
// ... For previously created applePayPaymentRequest object.
// Additionally set the shippingMethods.
applePayPaymentRequest.shippingMethods = [
{
"label": "Free Shipping",
"detail": "Arrives in 5 to 7 days",
"amount": "0.00",
"identifier": "free"
},
{
"label": "Express Shipping",
"detail": "Arrives in 1 to 2 days",
"amount": "5.99",
"identifier": "express"
}
];
// ... previously created session object (ApplePaySession).
// Set onshippingmethodselected event handler
session.onshippingmethodselected = function(event) {
// Recalculate the total amount based on the shipping method selected.
let shippingMethod = event.shippingMethod;
let subTotal = parseFloat("12.99"); // Price of order items.
let newCost = subTotal + parseFloat(shippingMethod.amount); // Adding shipping costs.
let updateObject = {
newTotal: {
"label": "Unzer GmbH",
"type": "final",
"amount": newCost.toString()
},
newLineItems: [
{
"label": "Bag Subtotal",
"type": "final",
"amount": "10.00"
},
{
"label": shippingMethod.label,
"type": "final",
"amount": shippingMethod.amount
}
]
};
session.completeShippingMethodSelection(updateObject);
}
// ... Add additional event handler functions.
Provide a Payment Authorized Endpointserver 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 paymentserver 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 paymentserver 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 resultclient 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 paymentserver 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.