Contents

Initialise SDK in your app

Warning
Ensure you have met all requirements before proceeding.

Click here for further information.

 

Configure the instance

Before you can perform any payment request, you will need to set the usernamegateway and environment, as shown in the example below:


TrustPayments.instance.configure(username: username_from_trustpayments,
                                 gateway: .eu,
                                 environment: .staging,
                                 translationsForOverride: nil
)

 

View controllers

There are three methods that can be used to add Apple Pay to your checkout:

  1. Add Apple Pay into existing drop-in view controller, allowing Apple Pay to be presented as payment option alongside the form asking for customer’s card details.
  2. Have your checkout only display Apple Pay as a payment option.
  3. Add Apple Pay to a custom view.

 

1. Add Apple Pay into existing drop-in view controller

This section describes how to include the Apple Pay button in the drop-in view controller.


// Minimum number of parameters
let request = PKPaymentRequest()
request.supportedNetworks = [.visa, .masterCard, .amex]
request.merchantCapabilities = [.capability3DS, .capabilityCredit, .capabilityDebit]
request.merchantIdentifier = "merchant.ios.trustpayments.test"
request.countryCode = "GB"
request.currencyCode = "GBP"

let applePayConfiguration = TPApplePayConfiguration(handler: self,
                                                    request: request,
                                                    buttonStyle: .black,
                                                    buttonDarkModeStyle: .white,
                                                    buttonType: .plain)
 
let dropInVC = try ViewControllerFactory.shared.dropInViewController(
    jwt: jwt,
    typeDescriptions: [.auth, .subscription],
    customDropInView: dropInCustomView,
    visibleFields: [.securityCode3],
    applePayConfiguration: applePayConfiguration,
    dropInViewStyleManager: dropInViewStyleManager,
    dropInViewDarkModeStyleManager: dropInViewDarkModeStyleManager,
    cardTypeToBypass: [.mastercard],
    cardinalStyleManager: cardinalStyleManager,
    cardinalDarkModeStyleManager: cardinalDarkModeStyleManager,
    payButtonTappedClosureBeforeTransaction: {
        (
            controller: DropInController
        )
    in},
    successfulPaymentCompletion: {
        (
            jwt: String,
            responses: [JWTResponseObject],
            successMessage: String,
            cardReference: TPCardReference?
        )
    in},
    transactionFailure: {
        (
            jwt: String?,
            responses: [JWTResponseObject]?,
            errorMessage: String,
            error: NSError?
        )
    in}
)

 

Parameter specification

Parameter Format Description
supportedNetworks
List The payment networks supported by the merchant. The value must be one or more of the following: “amex“, “masterCard” or “visa“.
merchantCapabilities
List The payment capabilities supported by the merchant.The field must contain “supports3DS” (to enable Touch ID / Face ID verification), and at least one of the following additional values:

  • “supportsCredit” – To enable credit card payments.
  • “supportsDebit” – To enable debit card payments.

For a full specification, please refer to Apple’s own documentation.

countryCode Alpha (2) The merchant’s country code in ISO2a format.
currencyCode Alpha (3) The transaction currency code in ISO3a format.
buttonDarkModeStyle
Alphanumeric Used to change the appearance of the Apple Pay button when device is in dark mode. Click here for further information.
buttonStyle Alphanumeric Used to change the appearance of the Apple Pay button when device is in light mode. Click here for further information.
buttonType Alphanumeric Used to change the text displayed on the Apple Pay button for different payment scenarios. Click here for further information.

 

External
Useful resources regarding the Apple Pay button

 

You can change the colour of the button and the text displayed to better suit the needs of your checkout.

Click here to learn more.

 

Apple has published guidelines on how to best position the Apple Pay button on your checkout.

Click here to learn more.

 

2. Configuring drop-in view controller to only show Apple Pay


// Minimum number of parameters
let request = PKPaymentRequest()
request.supportedNetworks = [.visa, .masterCard, .amex]
request.merchantCapabilities = [.capability3DS, .capabilityCredit, .capabilityDebit]
request.merchantIdentifier = "merchant.ios.trustpayments.test"
request.countryCode = "GB"
request.currencyCode = "GBP"
 
let applePayConfiguration = TPApplePayConfiguration(handler: self,
                                                    request: request,
                                                    buttonStyle: .black,
                                                    buttonDarkModeStyle: .white,
                                                    buttonType: .plain)
let dropInVC = try ViewControllerFactory.shared.dropInViewController(jwt: jwt,
                                                                          typeDescriptions: [.auth],
                                                                          customDropInView: nil,
                                                                          visibleFields: [],
                                                                          applePayConfiguration: applePayConfiguration,
                                                                          dropInViewStyleManager: dropInViewStyleManager,
                                                                          dropInViewDarkModeStyleManager: dropInViewDarkModeStyleManager,
                                                                          payButtonTappedClosureBeforeTransaction: nil,
                                                                          successfulPaymentCompletion: { (jwt, responses, successMessage, cardReference) in },
                                                                          transactionFailure: { (jwt, responses, errorMessage, error) in })

 

3. Add Apple Pay button to custom view

Add additional field wallettoken to your JWT payload, containing the string representation of the PKPayment token that you get after the Apple authorisation:


 let claim = TPClaims(iss: keys.merchantUsername,
                             iat: Date(timeIntervalSinceNow: 0),
                             payload: Payload(accounttypedescription: "ECOM",
                                              sitereference: keys.merchantSiteReference,
                                              currencyiso3a: "GBP",
                                              baseamount: 299,
                                              wallettoken: payment.stringRepresentation))
        guard let jwt = JWTHelper.createJWT(basedOn: claim, signWith: keys.jwtSecretKey) else { return }

        paymentTransactionManager.performWalletTransaction(walletSource: .applePay, jwt: jwt, typeDescriptions: [.auth], transactionSuccessClosure: { (jwt, responseObjects, _) in
            // Handle success as any other from payment manager
        }, transactionErrorClosure: { (jwt, responseObjects, errorMessage, errorObject) in
            // Handle error as any other from payment manager
        })

 

The token has to contain few fields provided by Apple:


let expectedJson: [String: Any] = [
            "token":
                [
                    "transactionIdentifier": self.token.transactionIdentifier,
                    "paymentData": paymentDataJson,
                    "paymentMethod":
                        [
                            "network": self.token.paymentMethod.network?.rawValue,
                            "type": self.token.paymentMethod.type.description,
                            "displayName": self.token.paymentMethod.displayName
                    ]
            ]
        ]

 

Extension that does that is included in the Example App files:


extension PKPayment {
    var stringRepresentation: String? {
        let paymentData = self.token.paymentData
        guard let paymentDataJson = try? JSONSerialization.jsonObject(with: paymentData,
                                                                      options: JSONSerialization.ReadingOptions(rawValue: 0)) as? [String: Any] else { return nil }
        let expectedJson: [String: Any] = [
            "token":
                [
                    "transactionIdentifier": self.token.transactionIdentifier,
                    "paymentData": paymentDataJson,
                    "paymentMethod":
                        [
                            "network": self.token.paymentMethod.network?.rawValue,
                            "type": self.token.paymentMethod.type.description,
                            "displayName": self.token.paymentMethod.displayName
                    ]
            ]
        ]
        guard let expectedJsonData = try? JSONSerialization.data(withJSONObject: expectedJson,
                                                                 options: JSONSerialization.WritingOptions(rawValue: 0)) else { return nil }
        return String(data: expectedJsonData, encoding: .utf8)
    }
}

 


 

Handling data update

If you allow users to update their shipping address and payment method on the Apple Pay form, you must conform to the TPApplePayConfigurationHandler protocol and handle the appropriate methods:


shippingMethodChanged(to method: PKShippingMethod, updatedWith: @escaping ([PKPaymentSummaryItem]) -> Void)

shippingAddressChanged(to address: CNPostalAddress, updatedWith: @escaping ([Error]?, [PKPaymentSummaryItem]) -> Void)

 

When conforming to those methods, you need to call updateWith closure with new PKPaymentSummaryItem, otherwise the authorisation will time out.

Also listen to didAuthorizedPayment(payment: PKPayment, updatedJWT: @escaping ((String?, [Error]?) -> Void)) method and provide updated JWT based on received PKPayment object.


 

Where next?

URL
Performing additional requests

 

For more advanced configurations, additional requests can be referenced in the drop-in view controller to perform additional actions.

Click here to learn how >>>