Apple Pay

Apple Pay lets Apple device users make easy, secure credit and debit card payments with a single click.

Supporting Apple Pay improves conversions and customer experience, and is quickly becoming essential for iOS payment apps. This seamless integration fosters loyalty, driving repeat business and enhancing your brand's reputation for innovation and convenience in the increasingly competitive mobile marketplace.

Before you start

Accepting Apple Pay payments through your N-Genius Online account relies on a number of pre-requisites, which you must be able to satisfy:

  • A valid and enrolled Apple Pay developer account (personal or organization)
  • An iOS app integrated with N-Genius Online

You can integrate Apple Pay with N-Genius by the following methods

  1. Using the N-Genius iOS SDK
  2. Direct Api Integration

Configuring Apple Pay

In order to begin accepting payments from Apple Pay users, you must first navigate to your N-Genius Online portal, log-in and browse to the Settings > Organisational hierarchy screen, and find the 'Payment channels' configuration option.

On the next screen, you will see a number of tabs indicating each type of payment channel, and how many are already configured.

Switch to the 'Wallets' tab to configure your Apple Pay integration.

Next, click on the 'certificate signing request' link to download the certificate signing request.

Upload this certificate signing request in Apple's developer portal to generate a new Payment processing certificate.

📘

Creating a payment processing certificate

You can navigate to Apple developer portal > Create new Payment processing certificate to create a new payment processing certificate.

On generating the payment processing certificate (PPC), upload the same on N-Genius portal by clicking the 'Upload signed certificate'.

On uploading the PPC, Apple pay is fully setup on your N-Genius Online account.

📘

Using Apple Pay in Third-Party Browsers

To ensure Apple Pay functions correctly in third-party browsers (such as Chrome or Firefox on iOS), include the official Apple Pay JavaScript SDK in the <head> of your HTML.

<head>
  <!-- Apple Pay JS SDK (required for third-party browsers) -->
  <script crossorigin 
    src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js">
  </script>
</head>

This script must be loaded before any Apple Pay logic runs on the page.

Integrating Apple app in-app

There are two ways to setup and configure Apple Pay in your iOS app

  1. NGenius SDK - Use the sdk to quickly integrate Apple Pay. (Order types supported: "AUTH","SALE")
  2. Direct API - You can directly integrate using the Apple Pay and NGenius apis to get more control.

Apple Pay (Direct API)

1. Enable Apple Pay in-app capabilities

Add your Merchant ID generated in Apple's Developer portal to your project's .entitlements file under Merchant IDs

2. Implement PKPaymentAuthorizationViewControllerDelegate

import PassKit

func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController,
                                            didSelect paymentMethod: PKPaymentMethod,
                                            handler completion: @escaping (PKPaymentRequestPaymentMethodUpdate) -> Void) {
            completion(PKPaymentRequestPaymentMethodUpdate(errors: nil, paymentSummaryItems: paymentSummaryItems))
    }
    
    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController,
                                            didSelect shippingMethod: PKShippingMethod,
                                            handler completion: @escaping (PKPaymentRequestShippingMethodUpdate) -> Void) {
            completion(PKPaymentRequestShippingMethodUpdate(paymentSummaryItems: paymentSummaryItems))
    }
    
    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController,
                                            didSelectShippingContact contact: PKContact,
                                            handler completion: @escaping (PKPaymentRequestShippingContactUpdate) -> Void) {
            completion(PKPaymentRequestShippingContactUpdate(errors: nil,
            paymentSummaryItems: paymentSummaryItems,
            shippingMethods: supportedShippingMethods))
    }
    
    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController,
                                            didAuthorizePayment payment: PKPayment,
                                            handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {
        self.onAuthorizeApplePayCallback(payment, {
            authorizationResult, paymentResponse in
            DispatchQueue.main.async {
                completion(authorizationResult)
                controller.dismiss(animated: false, completion: nil)
            }
        })
    }
    
    func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
        controller.dismiss(animated: false, completion: nil)
    }

3. Create the order on Gateway

Please refer the order creation API for creating an order on the gateway. Two stage payments

4. Authorize the Transaction on N-Genius

After successfully creating an order, the next step is to authorize the transaction by retrieving a special code and posting it to the payment-authorization endpoint.

This process issues a temporary payment-token that is required for processing the Apple Pay payload.


Step 1: Retrieve the Authorization Link

After creating the order, extract the following link from the _links.payment-authorization.href object in the order response:

"_links": {
  "payment-authorization": {
    "href": "https://api-gateway.sandbox.ngenius-payments.com/transactions/paymentAuthorization"
  }
}

This is the endpoint to which you’ll send the Apple Pay authorization request.


Step 2: Extract the Code

From the same response body, locate the payment link:

"payment": {
  "href": "https://paypage.sandbox.ngenius-payments.com/?code=3240d0b09acc80b9"
}

The code query parameter (in this case, 3240d0b09acc80b9) must be included in the authorization request body.


Step 3: Make the POST Request

Make a POST request to the payment-authorization endpoint using the headers and body format below:

Endpoint:
https://api-gateway.sandbox.ngenius-payments.com/transactions/paymentAuthorization

Headers:

Accept: application/vnd.ni-payment.v2+json
Media-Type: application/x-www-form-urlencoded
Content-Type: application/x-www-form-urlencoded

Body (as x-www-form-urlencoded):

code=3240d0b09acc80b9

Step 4: Retrieve the payment-token

The payment-token is returned in the response headers, not the body.

Look for the following key in the Set-Cookie response header:

Set-Cookie: payment-token=eyJraWQiOiJ...; Secure; HttpOnly;

You will extract the token value from this header and use it in the subsequent Apple Pay transaction.

📘

This payment-token is a temporary access token that must be used to authorize and complete the encrypted Apple Pay payload.


5. Create the PassKitPaymentRequest Object

This PKPaymentRequest object is required by Apple Pay. You can derive the required fields from the gateway order created. Also care must be taken to populate the merchantIdentifier field with the correct MID field configured in both the Apple's dev portal and N-Genius portal.

The paymentSummaryItems is an array of PKPaymentSummaryItem which has information related to the line items of items purchased by the user. This is displayed to the user in the Apple Pay interface. The last Item in this array represents the total cost or the order amount which the customer will be charged.

import PassKit

paymentRequest = PKPaymentRequest()
paymentRequest?.merchantIdentifier = "Insert Mid created in Apple dev portal here"
paymentRequest?.countryCode = "COUNRY CODE"
paymentRequest?.currencyCode = "CURRENCY CODE"
paymentRequest?.requiredShippingContactFields = [.postalAddress, .emailAddress, .phoneNumber]
paymentRequest?.merchantCapabilities = [.capabilityDebit, .capabilityCredit, .capability3DS]
paymentRequest?.requiredBillingContactFields = [.postalAddress, .name]
paymentRequest?.paymentSummaryItems = [PKPaymentSummaryItem(label: "Line Item", amount: NSDecimalNumber(value: amount))]
paymentRequest?.paymentSummaryItems.append(PKPaymentSummaryItem(label: "Total", amount: NSDecimalNumber(value: paymentAmount)))

6. Initiate Apple Pay in app

Initialise the Apple Pay View controller and instantiate it with the PKPaymentRequest object created previously.

import PassKit

let pkPaymentAuthorizationVC = PKPaymentAuthorizationViewController(paymentRequest: applePayRequest)

self.present(pkPaymentAuthorizationVC, animated: false, completion: nil)

7: Submit Apple Pay Encrypted Object to N-Genius

Once the user selects a card and authorises the payment via the Apple Pay sheet, Apple returns an encrypted object. This object must be forwarded to N-Genius to complete the transaction.

To do so:

Endpoint

Use the payment:apple_pay link provided in the order response. You’ll find this under:

_embedded.payment[0]._links["payment:apple_pay"].href

Example:

https://api-gateway.sandbox.ngenius-payments.com/transactions/outlets/{outlet-id}/orders/{order-id}/payments/{payment-id}/apple-pay

HTTP Request

  • Method: PUT

  • Headers:

    Authorization: Bearer {payment-token}
    Content-Type: application/vnd.ni-payment.v2+json
    
    • payment-token is retrieved from the Set-Cookie header in the response when posting to payment-authorization (Step 4).
  • Body:
    The Apple Pay encrypted object retrieved from the didAuthorizePayment method of the PKPaymentAuthorizationViewControllerDelegate. Only the paymentData field is required.

   {
  "applePayPaymentResponse": {
    "token": {
      "paymentData": {
        "data": "...",
        "signature": "...",
        "version": "...",
        "header": {
          "applicationData": "...",
          "ephemeralPublicKey": "...",
          "wrappedKey": "...",
          "publicKeyHash": "...",
          "transactionId": "..."
        }
      }
    }
  }
}

📘

Check if Apple Pay is setup

You can check if a user has setup Apple Pay on his device by making a call to PKPaymentAuthorizationViewController.canMakePayments(). This method will return a boolean value true if Apple pay is setup. You can use this method to conditionally render the Apple Pay button.

You can also check out Apple's guide to know which devices support Apple Pay

🚧

Troubleshooting Apple Pay Issues

While integrating with Apple Pay, if you encounter errors related to decryption or payment failures, this could be an issue of stale certificate being cached by Xcode. In such cases we recommend to create a new merchant identifier (MID) using a string value that has not been previously used in Apple's developer portal and re create the signed certificate against the new MID.

Apple Pay (N-Genius SDK)

Refer the SDK section for details on integrating Apple Pay using the N-Genius iOS SDK.