alt

Important information

Please be advised that there will be a scheduled downtime across our API network on November 05 and November 07, 2024. For more information, visit our platform status portal.:
- Scheduled maintenance on November 5, 2024
- Scheduled maintenance on November 7, 2024

Unzer

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

  • 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
icon
Apple Pay is only available for the Safari browser.

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

Load 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>
icon
Faster load time
To make your website load faster, insert JavaScript scripts at the bottom of your HTML document.
icon
Importing Unzer styles
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');
icon
Placeholder keys
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

Create 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.

Inside your onclick() event handler you will need to proceed with the following steps. Below you can see a full Example.

Create a payment type instance
client side

To create a payment type instance – an ApplePay instance, call the unzerInstance.ApplePay() function.

const unzerApplePayInstance = unzerInstance.ApplePay()
    

Create an Apple Pay Payment Request and Session
client 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"
            }
        ]
};

The created payment request can then be used to create the ApplePaySession. You can either create the session on you own or by calling unzerApplePayInstance.initApplePaySession().

icon
By calling unzerApplePayInstance.initApplePaySession() a default implementation of onvalidatemerchant is provided.
// We use Apple Pay version 6 as default. 
// If you need to use another version you can set it in the second parameter. e.g initApplePaySession(applePayPaymentRequest, 7)
// This will provide a default onvalidatemerchant implementation
const session = unzerApplePayInstance.initApplePaySession(applePayPaymentRequest)

Start the Apple Pay session
client side

By calling the session.begin() method on the session object 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 start the merchant validation process.
session.begin();

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 handlerDescription
onpaymentauthorized

(required)
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.
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
    const 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. For example, show error.message in the frontend.
            abortPaymentSession(session);
        })
}

Full example


function yourOnClickHandlerMethod() {
    const unzerApplePayInstance = unzerInstance.ApplePay()
    
    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"
                }
            ]
    };

    const session = unzerApplePayInstance.initApplePaySession(applePayPaymentRequest)
    
    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
        const 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. For example, show error.message in the frontend.
                abortPaymentSession(session);
            })
    }
    
    // Add additional event handler functions ...
    
    // start the merchant validation process 
    session.begin();
}

Express Checkout
client 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.

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'],
};
In the 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 and start the session.

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

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

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

We 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

All 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

You 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.

See also