---
title: iOS
slug: ios
docTags: 
createdAt: 2024-06-12T10:31:29.077Z
---

# Integrating iOS with Judopay

:::hint{type="warning"}
We are currently working on updating the Swift sample app.
See our Sample Apps [here](https://github.com/Judopay/JudoKit-iOS/tree/master/Examples).
:::

## Prerequisites

- You have set up your Judopay account.
  - Sign up for your [sandbox account](https://www.judopay.com/apply-sandbox-account), to receive access to your Judopay dashboard and the sandbox environment.
- Your judoIds and tokens are configured and enabled as appropriate.
  - For more information on permissions, see [Permissions](docId\:S_8hOAMytkgY13t0P657-).
- You have the latest version of the iOS SDK.

:::hint{type="info"}
For Mobile apps, we recommend using **[payment session authentication](docId\:ylKW5coh5NQnfQ3j_Wjk2)**.
:::

***

### Integrating via Swift Package Manager (SPM)

1. Search for [JudoKit-iOS.](https://github.com/Judopay/JudoKit-iOS)
2. Add JudoKit-iOS to your Package Dependencies.

***

### Integrating via CocoaPods

**Step One - To integrate the iOS mobile SDK via CocoaPods**:

1. Install CocoaPods with the following command: `gem install cocoapods`
2. Via the terminal, navigate to your project's root directory
3. Initialize CocoaPods with the following command: `pod init`
4. A podfile is generated in the root directory

**Step Two - To add the mobile SDK as a dependency**:

1. Open the podfile and add the following: `pod 'JudoKit-iOS'`
2. Install the dependency with the following command: `pod install`

The **Pod installation complete!** message appears in the terminal.

If th&#x65;**&#x20;Unable to find a specification** error message appears, your CocoaPods repository, which stores a reference to all available pods, needs updating.
To update your CocoaPods repository run: `$ pod repo update`

:::hint{type="warning"}
Ensure you always use the generated **.xcworkspace&#x20;**&#x66;ile instead of the .xcodeproj file.
:::

***

### Integrating via Carthage

To integrate the iOS Mobile SDK via Carthage:

1. Install [Carthage](https://github.com/Carthage/Carthage) on your machine:
   1. Using brew (terminal): brew install carthage
2. In the root folder of your project, add a new file named **Cartfile**
3. In Cartfile, add all the dependencies you need:
   For the purpose of this exercise: **github "Judopay/JudoKit-iOS"**
4. In the terminal run the following command:
   `carthage update--use-xcframeworks--platform ios`
5. Check your root folder has the following:
   1. Cartfile.resolved (File with all downloaded dependencies, including their versions)
   2. Carthage folder
6. In Xcode, manually drag and drop the JudoKit-iOS xcframework and all the dependent xcframeworks into:
   1. Linked Frameworks
   2. Libraries section
      Frameworks are stored in folder **Carthage > Build**
7. Rebuild the project
8. Import the JudoKit-iOS into your project files: `#import <JudoKit-iOS/JudoKit_iOS.h>`

The iOS Mobile SDK is now ready to use in your iOS project.

***

## Initialising a JudoKit Session

To get started:

To access the **JudoKit&#x20;**&#x63;lass, import the **JudoKit\_iOS** framework:
`#import <JudoKit_iOS/JudoKit_iOS.h>`

To initialise a JudoKit session:

:::hint{type="info"}
The difference between a **basic&#x20;**&#x61;uthentication method and a **session&#x20;**&#x61;uthentication method is:

- Basic authentications last indefinitely.
- Session authentications are valid for **one&#x20;**&#x74;ransaction. This offers a more secure authentication approach.
:::

:::hint{type="warning"}
Merchants operating in specific money movement and financial services categories, as defined by the card schemes **must include** additional data in the [payment session](docId\:ylKW5coh5NQnfQ3j_Wjk2).
For more information, see [Account Funding Transactions](docId:5ol_pTSGBHVGKwJwD0gHg).
:::

1. Use either a basic (token\:secret) authentication method, or a session (token & session) authentication method.
2. Create a basic authentication instance:
   `JPBasicAuthorization *authorization = [JPBasicAuthorization authorizationWithToken:@"token" andSecret:@"secret"]`
3. Create a payment session authentication instance:
   `JPSessionAuthorization *authorization = [JPSessionAuthorization authorizationWithToken:@"token" andPaymentSession:@"session token"]`

To create a JudoKit session:&#x20;
`JudoKit *judo = [[JudoKit alloc] initWithAuthorization:authorization];`

To communicate with the sandbox environment, enter:
`judo.isSandboxed = YES;`

:::hint{type="info"}
By default, Judopay allows jailbroken devices to access it's features. If you would like to restrict access to non-jailbroken devices only, use this initializer instead:
`JudoKit *judo = [[JudoKit alloc]initWithAuthorization:authorization "allowJailbrokenDevices:NO];`
:::

***

## Setting the Parameters for a Successful Transaction

Use the **JPConfiguration** object to set the parameters.&#x20;
The JPConfiguration object is passed as a method parameter and communicates how the payment flow should behave.

To configure the **JPConfiguration** object, add your:

- JudoId
  - **JudoId format = 100100100**
- Amount
- ConsumerReference

:::BlockQuote
JPAmount \*myAmount;
JPReference \*myReference;
JPConfiguration \*myConfiguration;

&#x20;myAmount = \[\[JPAmount alloc] initWithAmount:@"0.01"
&#x20;currency:@"GBP"];

&#x20;myReference = \[\[JPReference alloc] initWithConsumerReference:@"my-reference"];

&#x20;myConfiguration = \[JPConfiguration alloc] initWithJudoID:@"my-judo-id"
&#x20;amount\:myAmount
&#x20;reference\:myReference];
:::

The **JPAmount** object sets your:

- Transaction amount
- Currency code

The **JPReference&#x20;**&#x6F;bject sets your reference details, for example your unique **consumerReference**, to identify your consumer.
Now you can use this object to make a transaction.

***

## Making a Transaction

:::hint{type="info"}
3D Secure 2 is available on Judokit iOS **version 3.0.0** or higher, and is available on [Github](https://github.com/Judopay/JudoKit-iOS/releases/tag/v3.0.0).
(Currently supports Visa and Mastercard. Amex coming soon).&#x20;
:::

### Prerequisites

1. You have integrated with the [Mobile SDK](docId:09p1crU0CbxJkzEa-0ZPI)
2. You have set up the **JPConfiguration** instance with all the required properties

:::hint{type="info"}
Card validation | Card formatting | Type | Detection | is handled by Judopay.
:::

The available transaction types that can be passed as a parameter are:

- Payment
- PreAuth
- Check Card
- Save Card

For more details, see our [Transaction API Reference](https://docs.judopay.com/api-reference/index.html#/) documentation.

Once you have completed the prerequisite steps, you are ready to make a transaction.
To make a transaction:

1. Call the method and handle the response from the completion block:

:::BlockQuote
\[judo invokeTransactionWithType\:TransactionTypePayment
&#x20;configuration\:configuration
&#x20;completion:^(JPResponse \*response, JPError \*error) \{

&#x20;// Handle response / error

}];
:::

| **Name**        | **Type**                | **Description**                                                       |
| --------------- | ----------------------- | --------------------------------------------------------------------- |
| `type`          | TransactionType         | An enum value that sets the transaction type.                         |
| `configuration` | JPConfiguration         | An object that configures the payment flow.                           |
| `completion`    | JPResponse<br />JPError | A completion block that returns the transaction response or an error. |

***

### User Interface

**Pre-Built UI Component (Recommended)**
If you are using th&#x65;**&#x20;pre-built UI component** provided with our SDK, see [Using the Pre-Built UI Card Entry Component](docId:09p1crU0CbxJkzEa-0ZPI).
To configure the fields displayed in the default card entry UI, see [Configuring the UI.](docId\:prT4F78QMrSJU1gHJAWGM)

**Custom UI Component**
If you are building your own **custom UI component**, see [Using your own Custom Card Entry UI](docId:09p1crU0CbxJkzEa-0ZPI).

***

### iOS Server to Server Transactions

The SDK also offers server-to-server capabilities.&#x20;
This works by sending the payment token back to the merchant the moment the consumer presses the Pay button.
This allows the merchant to process and complete the transaction on their side.

Server-to-server capabilities are available for both transactions made through:

- The Payments Widget
- Apple Pay™

To specify a server-to-server transaction:

:::CodeblockTabs
Server to Server Example

```objective-c
//Set the TransactionMode to TransactionModeServerToServer when calling the Judopay methods:

[judo invokePaymentMethodScreenWithMode:TransactionModeServerToServer
                          configuration:configuration
                             completion:^(JPResponse *response, JPError *error) {
    // Handle the payment token returned from the response
}];
 

//Specify an Apple Pay™ transaction:

[judo invokeApplePayWithMode:TransactionModeServerToServer
               configuration:configuration
                  completion:^(JPResponse *response, JPError *error) {
    // Handle the payment token returned from the response
}];
```
:::

***

### Token Payments and Preauths

If you are building your own card wallet, and not using a UI you can make a `/payments` or `/preauths` transaction using a stored **card token**.

1. Follow the steps for [Making a Transaction](docId:09p1crU0CbxJkzEa-0ZPI)
2. To make a token transaction:

:::CodeblockTabs
Token Transaction Request

```objective-c
//Call the method and handle the response from the completion block:

[judo invokeTokenTransactionWithType:JPTransactionTypePayment 
                configuration:configuration 
                details:cardTransactionDetails completion:^(JPResponse *response, JPError *error) 
{ 
    // Handle response / error
}];
```
:::

***

### Using the Pre-Built UI Card Entry Component (Recommended)

The easiest way to integrate 3D Secure is to use the **pre-built UI component** within JudoKit, as this handles the 3D Secure flow for you.
Using a 3D Secure Enabled credential, follow the steps for [Making a Transaction](docId:09p1crU0CbxJkzEa-0ZPI).

:::hint{type="warning"}
We recommend using **billingAddress&#x20;**&#x61;nd **emailAddress&#x20;**&#x66;ields for **3D Secure 2&#x20;**&#x74;ransactions.
:::

:::CodeblockTabs
Pre Built Card Entry UI

```objective-c
JPAmount *amount = [[JPAmount alloc] initWithAmount:@"1.50" currency:@"GBP"];
JPReference *reference = [[JPReference alloc] initWithConsumerReference:@"consumer-reference" paymentReference:@"payment-reference"];

JPUIConfiguration *uiConfiguration = [JPUIConfiguration new];

// sets whether 3DS 2.0 UI billing information screen should be presented to the user
uiConfiguration.shouldAskForBillingInformation = YES;

// in case you don't want to present billing info screen to the user, you can set the address instead
JPAddress *address = [[JPAddress alloc] initWithAddress1:@"My house"
                                                address2:@"My street"
                                                    town:@"My town"
                                          billingCountry:@"826"
                                                postCode:@"TR14 8PA"
                                             countryCode:@826];

JPConfiguration *configuration = [[JPConfiguration alloc] initWithJudoID:@"my-judo-id" amount:amount reference:reference];
configuration.uiConfiguration = uiConfiguration;

configuration.cardAddress = address;


// sets the value for challenge request indicator,
// possible values:
//
// noPreference
// noChallenge
// challengePreferred
// challengeAsMandate
//
configuration.challengeRequestIndicator = @"challengeAsMandate";

// sets the value for SCA exemption,
// possible values:
//
// lowValue
// secureCorporate
// trustedBeneficiary
// transactionRiskAnalysis
//
configuration.scaExemption = @"lowValue";

// email address
configuration.emailAddress = @"email@me.com";

// sets the maximum timeout for 3DS 2.0 transactions in minutes,
// always use 2 characters when setting the timeout
configuration.threeDSTwoMaxTimeout = 30;

// sets phone number country code
configuration.phoneCountryCode = @"44";

// phone number
configuration.mobileNumber = @"11223344556677";
```
:::

***

### Using your own Custom Card Entry UI

You can implement a customisable UI layer, to replace the [Pre-Built UI Component](docId:09p1crU0CbxJkzEa-0ZPI) provided with Judopay's iOS SDK.

:::hint{type="warning"}
This customisation **does not** extend to the 3D Secure 2 flow, which remains unchanged and cannot be currently over-ridden.
:::

***

**Prerequisites**

From the **Integrating** **iOS with Judopay&#x20;**&#x67;uide, you have completed the following:

- [Initialised a Judokit Session](docId:09p1crU0CbxJkzEa-0ZPI).
- [Set up the JPConfiguration instance](docId:09p1crU0CbxJkzEa-0ZPI) with all the required properties.

***

**Setting up your Custom Card Entry UI**

**Step One:**

1. Initiate the `JPCardTransactionService`

:::CodeblockTabs
Initiate TransactionService

```objective-c
JPCardTransactionService *transactionService = [[JPCardTransactionService alloc] initWithAuthorization:self.authorization
   isSandboxed:false
   andConfiguration:self.configuration];
```
:::

***

**Step Two:**

1. Initiate a `JPCardTransactionDetails` object.
2. Populate the object with the necessary card details.
   These are the details you wish to capture in your custom UI layer.

:::CodeblockTabs
Initiate Object

```objective-c
JPCardTransactionDetails *cardTransactionDetails = [JPCardTransactionDetails new];
cardTransactionDetails.cardNumber = @"4976350000006891";
cardTransactionDetails.cardholderName = @"John Smith";
cardTransactionDetails.expiryDate = @"12/30";
cardTransactionDetails.securityCode = @"123";
(...) // Other transaction details (e.g. billing address)
```
:::

Use one of the following methods on the `CardTransactionService` instance to initiate the following transaction types:

- &#x20;invokePaymentWithDetails
- &#x20;invokePreAuthPaymentWithDetails
- invokeCheckCardWithDetails
- invokeSaveCardWithDetails

***

**Processing a Payment**

Call the `invokePaymentWithDetails` method and handle the response from the completion block:

:::CodeblockTabs
invokePayment

```objective-c
[self.transactionService invokePaymentWithDetails:cardTransactionDetails
        andCompletion:^(JPResponse *response, JPError *error) {
        // Handle the transaction result (including error case) here.
}];
```
:::

***

**Processing a Pre-Authorisation&#x20;**

Call the `invokePreAuthPaymentWithDetails` method and handle the response from the completion block:

:::CodeblockTabs
invokePreAuthPayment

```objective-c
[self.transactionService invokePreAuthPaymentWithDetails:cardTransactionDetails
          andCompletion:^(JPResponse *response, JPError *error) {
         // Handle the transaction result (including error case) here.
}];
```
:::

***

**Performing a Check Card Request**

Call the `invokeCheckCardWithDetails` method and handle the response from the completion block:

:::CodeblockTabs
invokeCheckCard

```objective-c
[self.transactionService invokeCheckCardWithDetails:cardTransactionDetails
          andCompletion:^(JPResponse *response, JPError *error) {
         // Handle the transaction result (including error case) here.
}];
```
:::

***

**Performing a Save Card Request**

Call the `invokeSaveCardWithDetails` method and handle the response from the completion block:

:::CodeblockTabs
invokeSaveCard

```objective-c
[self.transactionService invokeSaveCardWithDetails:cardTransactionDetails
          andCompletion:^(JPResponse *response, JPError *error) {
         // Handle the transaction result (including error case) here.
}];
```
:::

***

## Setting up Recurring Payments

Make sure you are using:

- IOS SDK **Version 6.5.0** (or higher)

:::hint{type="warning"}
Integration via React Native Mobile SDK is not currently supported.
:::

Judopay provides support for Apple Pay™ recurring and deferred Merchant Initiated Transactions (MIT)s for Wallet Customer Initiated Transactions (CIT)s.&#x20;

This feature enables merchants to utilise the Apple Pay™ recurring / deferred payment token, by also being able to use the token for Merchant-Initiated Transactions (MITs).

The Apple Pay™ recurring  / deferred payment token is generated by Apple Pay's servers and sent to Judopay, where it is securely stored.&#x20;
In return, you will receive a Judopay token that is linked to the stored Apple Pay™ token.&#x20;
This Judopay token can then be used for future MITs.&#x20;

### Recurring Payments

:::hint{type="warning"}
Make sure you are using iOS version **16.0+** to enable recurring payments.
(guard with if #available).
:::

To trigger an initial transaction that allows you to set up an Apple Pay™ recurring payment token for future Merchant Initiated Transactions (MIT):

1. Attach the recurring payment configuration object `JPRecurringPaymentRequest` to your [Apple Pay™ configuration](docId:09p1crU0CbxJkzEa-0ZPI):
2. Set the `isInitialRecurringPayment` flag in the Judopay configuration object to **true**.&#x20;
3. Invoke with the existing `invokeApplePay(with:configuration:completion:)`

:::CodeblockTabs
Recurring Payments Example

```objective-c
import JudoKit_iOS

let total = JPPaymentSummaryItem(label: "Premium Plan",
                                 amount: NSDecimalNumber(string: "25.00"))

let appleConfig = JPApplePayConfiguration(merchantId: "<APPLE_MERCHANT_ID>",
                                          currency: "GBP",
                                          countryCodse: "GB",
                                          paymentSummaryItems: [total])

if #available(iOS 16.0, *) {
    let regularBilling = JPRecurringPaymentSummaryItem(
        label: "Premium Plan — monthly",
        amount: NSDecimalNumber(string: "25.00"),
        intervalUnit: .month,
        intervalCount: 1,
        startDate: Date(),          // first billing date
        andEndDate: nil)            // nil -> open-ended subscription

    let request = JPRecurringPaymentRequest(
        paymentDescription: "Premium Plan subscription",
        regularBilling: regularBilling,
        andManagementURL: URL(string: "https://merchant.example.com/subscriptions")!)
    request.billingAgreement = "Subscription auto-renews until cancelled."

    appleConfig.recurringPaymentRequest = request
}

let config = JPConfiguration(judoID: "<JUDO_ID>",
                             amount: JPAmount("25.00", currency: "GBP"),
                             reference: reference)
config.applePayConfiguration = appleConfig
// First charge taken now, alongside mandate setup:
config.isInitialRecurringPayment = true

judoKit.invokeApplePay(with: .payment, configuration: config) { response, error in
    // handle result
}
```
:::

Judopay acts as &#x61;**&#x20;pass-through service**, whereby we supply the data needed by Apple Pay™ for them to return a device / merchant specific token that can be used for MIT transactions.&#x20;

For a full description on all the object properties in the Apple Pay™ recurring payments flow, see the [Apple Pay™ Documentation](https://developer.apple.com/documentation/passkit/pkpaymentrequest/recurringpaymentrequest).

***

### Deferred Payments

:::hint{type="warning"}
Make sure you are using iOS version **16.4+** to enable deferred payments.
(guard with if #available).
:::

To trigger an initial transaction that allows you to set up an Apple Pay™ deferred payment token for future Merchant Initiated Transactions (MIT):

1. Attach the deferred payment configuration object `JPDeferredPaymentRequest` to your [Apple Pay™ configuration](docId:09p1crU0CbxJkzEa-0ZPI)
2. Invoke with the existing `invokeApplePay(with:configuration:completion:)`

:::CodeblockTabs
Deferred Payment Example

```objective-c
import JudoKit_iOS

let total = JPPaymentSummaryItem(label: "Hotel room reservation",
                                 amount: NSDecimalNumber(string: "200.00"))

let appleConfig = JPApplePayConfiguration(merchantId: "<APPLE_MERCHANT_ID>",
                                          currency: "GBP",
                                          countryCode: "GB",
                                          paymentSummaryItems: [total])

if #available(iOS 16.4, *) {
    let deferredBilling = JPDeferredPaymentSummaryItem(
        label: "Hotel room reservation",
        amount: NSDecimalNumber(string: "200.00"),
        deferredDate: Calendar.current.date(from: DateComponents(year: 2027, month: 1, day: 1))!)

    let request = JPDeferredPaymentRequest(
        paymentDescription: "Hotel room reservation",
        deferredBilling: deferredBilling,
        andManagementURL: URL(string: "https://merchant.example.com/bookings")!)
    request.billingAgreement = "Your card will be charged on the billing date shown."
    // Optional: date until which the shopper can cancel for free
    request.freeCancellationDate = Calendar.current.date(from: DateComponents(year: 2026, month: 12, day: 25))
    request.freeCancellationDateTimeZone = TimeZone(identifier: "Europe/London")

    appleConfig.deferredPaymentRequest = request
}

let config = JPConfiguration(judoID: "<JUDO_ID>",
                             amount: JPAmount("200.00", currency: "GBP"),
                             reference: reference)
config.applePayConfiguration = appleConfig

judoKit.invokeApplePay(with: .payment, configuration: config) { response, error in
    // handle result
}
```
:::

Judopay acts as &#x61;**&#x20;pass-through service**, whereby we supply the data needed by Apple Pay™ for them to return a device / merchant specific token that can be used for MIT transactions.&#x20;

For a full description on all the object properties in the Apple Pay™ deferred payments flow, see the [Apple Pay™ Documentation](https://developer.apple.com/documentation/passkit/pkpaymentrequest/deferredpaymentrequest).

***

## Adding Payment Methods

:::hint{type="warning"}
Before you can process Apple Pay™ payments with Judopay, you will need to set up Apple Pay™.
:::

:::::ExpandableHeading
### Setting up Apple Pay for iOS

:::hint{type="warning"}
Apple Pay™ is not supported on all Apple devices.
:::


Before invoking any Apple Pay™ functionality within your app, test if it is supported on the device by performing these checks:
`Use PKPaymentAuthorizationViewController canMakePayments`

- Checks if the device supports Apple Pay™ and has it enabled.
- Queries both the device hardware and whether Apple Pay™ is enabled in the user’s region

`Use PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks`

- A more detailed check to query whether a user has a registered card with particular card schemes.
- Useful if you do not accept all card types.

Both methods are explained in the Apple developer documentation [here](https://developer.apple.com/documentation/passkit/pkpaymentauthorizationviewcontroller).

***


**Getting Your Apple Pay™ Account**
**System Requirements**:

-  A compatible Apple device: iPhone 6 & 6 Plus | iPad Air 2 | iPad mini 3 | or newer
- iOS 12.0 or newer
- Xcode 14.0 or newer



***

**Create a Merchant ID**
We recommend creating a Merchant ID for each Merchant (i.e. business) accepting payments within your app.

**To set up your Apple Pay™ account**:

::Image[]{src="https://api.archbee.com/api/optimize/QGXTyW3MgdNcMjdEa0v8r/N22ye9WD7HwTOgWsF4opQ_ap-for-mobile.png" size="74" width="630" height="511" position="flex-start" alt="set up apple pay account" darkWidth="630" darkHeight="511" showCaption="false"}

::::WorkflowBlock
:::WorkflowBlockItem
Access your Apple Developer Account.
Navigate to **Certificates, Identifiers & Profiles**.
:::

:::WorkflowBlockItem
From the side menu, click **Merchant IDs**.
:::

:::WorkflowBlockItem
In the iOS Merchant ID Settings screen, click the **add&#xA0;**&#x62;utton.
:::

:::WorkflowBlockItem
Set your **Merchant ID**.
The identifier you enter should be a reverse DNS style identifier prefixed with the word.
:::

:::WorkflowBlockItem
Click **Done**.
:::
::::

***


**Create an Apple Pay™ Certificate**
 
**Prerequisite**
Request a Certificate Signing Request (CSR) file from Judopay.
When you’ve received your CSR, you can create your Apple Pay™ certificate.
 
To create your Apple Pay™ certificate:

::Image[]{src="https://api.archbee.com/api/optimize/QGXTyW3MgdNcMjdEa0v8r/o4mfSY0Osv7HGQjAaliex_ap-for-mobile-6.png" size="82" width="742" height="800" position="center" alt="create apple pay certificate" darkWidth="742" darkHeight="800" showCaption="false"}

::::WorkflowBlock
:::WorkflowBlockItem
From the side menu, select either:

-  Certificates > All
- Merchant ID
:::

:::WorkflowBlockItem
The screen appears describing how to manually create your Certificate Signing Request (CSR).
As you’ve already obtained your CSR from Judopay, click **Continue**.
:::

:::WorkflowBlockItem
You will be prompted to state if you are processing transactions outside the United States.
Select **No**.
:::

:::WorkflowBlockItem
Click **Continue**.
:::

:::WorkflowBlockItem
Click Choose File to upload the CSR file provided by Judopay.
:::

:::WorkflowBlockItem
Click **Generate**.
:::

:::WorkflowBlockItem
The confirmation screen appears.
Your certificate is ready to download.
Click **Download**.
:::

:::WorkflowBlockItem
Click **Done**.
To complete your Apple Pay™ set-up send the certificate to Judopay.
Once received, we will add the certificate to your account and confirm it has been added.
:::
::::

:::hint{type="info"}
Apple Certificates expire just over two years after generation.&#x20;
For example a certificate generated on 13th May 2024 will expire on the 11th June 2025.
Refer to your Apple Developer Account for an accurate expiry date.
**To generate a new certificate follow the steps above**.
:::

***

**Set Up Apple Pay™ Entitlement**
Apple Pay™ is built into the PassKit framework, which means you will need to configure the entitlement.
 
To set up the entitlement:

::Image[]{src="https://api.archbee.com/api/optimize/QGXTyW3MgdNcMjdEa0v8r/AHYMjhkl4eLuyxPIzdMjf_ap-for-mobile-10.png" size="58" width="426" height="800" position="flex-start" alt="set up apple pay entitlement" darkWidth="426" darkHeight="800" showCaption="false"}

::::WorkflowBlock
:::WorkflowBlockItem
Select your build Target.
:::

:::WorkflowBlockItem
Select Capabilities.
:::

:::WorkflowBlockItem
Set the entitlement to Enabled.
:::

:::WorkflowBlockItem
Add the Merchant ID created earlier to the app.
You may need to refresh the list.
:::

:::WorkflowBlockItem
Open the entitlements file to confirm the Merchant ID has been added to your app.
:::
::::

Your account is now ready to process Apple Pay™ payments with Judopay. 
Configure the [ iOS Mobile SDK ](docId:09p1crU0CbxJkzEa-0ZPI) to start making payments.

***

**Apple Pay™ Button**
 
Apple Pay™ allows the consumer to:

-  Bypass the standard checkout flow
- Complete their payment with speed

::Image[]{src="https://api.archbee.com/api/optimize/QGXTyW3MgdNcMjdEa0v8r/biAQ25ZKJYzFMByE80NnZ_ap-for-mobile-11.png" size="74" width="800" height="538" position="flex-start" alt="apple pay button" darkWidth="800" darkHeight="538" showCaption="false"}

When integrating with Apple Pay™, it is recommended to consider when to introduce the Apple Pay™ button.
This can be:

-  On a single item product listing page
- Within a basket page with multiple items
- Both of the above scenarios

The Apple Pay™ button enables consumers to make a purchase from the specific page they are browsing.
By tapping the Apple Pay™ button, the payment sheet is invoked to begin the checkout process.
 
For more information on the Apple Pay™ button, see Apple’s guidance of the **PKPaymentButton&#x20;**&#x43;lass Reference.

***

**Best Practice Testing**

:::hint{type="info"}
You can test Apple Pay™ in the sandbox environment with the sandbox cards, however please note these test transactions will **not work going upstream**.
To test Apple Pay™ transactions, point to the **live&#x20;**&#x65;nvironment and use **live cards**.

We recommend performing | Pre-Authorizations | Card Payments | Full Refunds: via the **Judopay Dashboard > History**, or via an **API call**
:::




We strongly recommend testing Apple Pay™ through each of these scenarios before you release the app:

-  **Unsupported Device**
  - Use a non-supported device in order to verify the whole recognition workflow works as expected.
- **Card not Supported**
  - Use a card issued by a bank that does not support Apple Pay™. You can also use the test cards provided on the Judopay Dashboard to validate the error returned and expected behaviour.
- **Payment Cancelled**
  - Cancel a transaction in process and see the results in the app and in your Judopay Dashboard history.
- **Poor / Loss of Connection**
  - While a transaction is being processed, disconnect the internet connection to see if the app responds as expected.
:::::

::::ExpandableHeading
### Configuring Apple Pay for iOS

To configure Apple Pay™:

1. Add the Apple Pay™ configuration
2. Call the Apple Pay™ method

**Step One: Adding the Apple Pay™ Configuration**
All Judo transactions require a **JPConfiguration** instance passed as a method parameter.
The basic JPConfiguration **requires**:

- Judo ID
- Amount
- Consumer reference

:::hint{type="warning"}
Apple Pay™ transactions require additional parameters in order to work correctly.
:::

To set all the Apple Pay™ required parameters, use the **JPApplePayConfiguration**:

:::BlockQuote
NSDecimalNumber \*itemOnePrice = \[NSDecimalNumber decimalNumberWithString:@"649.99"];
NSDecimalNumber \*itemTwoPrice = \[NSDecimalNumber decimalNumberWithString:@"55.00"];
NSDecimalNumber \*totalPrice = \[NSDecimalNumber decimalNumberWithString:@"704.99"];

NSArray \*mySummaryItems = @\[&#x20;
\[JPPaymentSummaryItem itemWithLabel:@"iPhone XR 254GB" amount\:itemOnePrice],&#x20;
\[JPPaymentSummaryItem itemWithLabel:@"iPhone XR Case" amount\:itemTwoPrice],&#x20;
\[JPPaymentSummaryItem itemWithLabel:@"Apple Store" amount\:totalPrice],
];
:::

:::hint{type="info"}
For each item you wish to list, you will need to sum up the item in the basket.
:::

**Payment summary items**:
This is a list of **JPPaymentSummaryItem** objects, that describe the item being purchased, including the price.&#x20;
In the example above, the item **label** was set to the merchant from where the item was purchased.

This is how the **JPApplePayConfiguration&#x20;**&#x6C;ooks:

:::BlockQuote
NSArray \*mySummaryItems

JPApplePayConfiguration \*applePayConfig;
applePayConfig = \[\[JPApplePayConfiguration alloc] initWithMerchantId:@"my-merchant-id"
&#x20;currency:@"GBP"&#x20;
countryCode:@"GB"&#x20;
paymentSummaryItems\:mySummaryItems
];

:::

| **Parameter**<br />****            | **Description**<br />                                                      |
| ---------------------------------- | -------------------------------------------------------------------------- |
| `merchantId`<br />NSString         | Your Apple Pay™ merchant ID.This confirms you are able to accept payments. |
| `currency`<br />NSString           | An ISO 4217 currency code.                                                 |
| `countryCode`<br />NSString        | An ISO 3166-1 Alpha-2 country code.                                        |
| `paymentSummaryItems`<br />NSArray | The list of items.                                                         |

:::hint{type="info"}
The last item in the array should always represent the total amount.
:::

**Step Two - Add the instance to the object**

1. Add the **JPApplePayConfiguration** instance to the **JPConfiguration** object:
   `configuration.applePayConfiguration = applePayConfig;`
2. Call the Judo method
3. Invoke Apple Pay™ by providing the **TransactionMode**
   This allows you to select:
   1. Payment or,
   2. PreAuth
4. Set the Apple Pay™ configuration:

:::BlockQuote
\[judo invokeApplePayWithMode\:TransactionModePayment&#x20;
configuration\:myApplePayConfiguration&#x20;
completion:^(JPResponse \*response, JPError \*error) \{&#x20;
// Handle response or error
}];
:::
::::

::::ExpandableHeading
### Displaying Apple Pay for iOS

To display Apple Pay™ as a payment method:

1. Configure th&#x65;**&#x20;JPApplePayConfiguration** object
2. From the JPConfiguration already created, call:

:::BlockQuote
\[\[judo invokePaymentMethodScreenWithMode\:TransactionModePayment&#x20;
configuration\:configuration&#x20;
completion:^(JPResponse \*response, JPError \*error) \{
// Handle the response and error
}];
:::

:::hint{type="info"}
In the example, the **TransactionMode is** set as the first method parameter.&#x20;
:::

***

**Adding the Billing and Shipping Details**

If you would like the consumer to provide their billing and shipping details, set the following properties:

- requiredBillingContactFields&#x20;
- requiredShippingContactFields

You can choose between multiple contact field types:

- email address&#x20;
- phone number&#x20;
- post code

For example:

:::BlockQuote
applePayConfig.requiredBillingContactFields = JPContactFieldName | JPContactFieldEmail;
applePayConfig.requiredShippingContactFields = JPContactFieldAll;
:::

| **Parameter**                 | **Description**                 |
| ----------------------------- | ------------------------------- |
| `JPContactFieldName`          | Consumer's name.                |
| `JPContactFieldEmail`         | Consumer's valid email address. |
| `JPContactFieldPhone`         | Consumer's valid phone number.  |
| `JPContactFieldPostalAddress` | Consumer's postal address.      |
| `JPContactFieldAll`           | All the values above.           |

If you set shipping details as a **required&#x20;**&#x66;ield, you must also set the **shippingType&#x20;**&#x61;nd the **shippingMethods** properties.&#x20;

**To set the shipping type**:

:::BlockQuote
applePayConfig.shippingType = JPShippingTypeDelivery;
:::

| **Parameter**                 | **Description**                   |
| ----------------------------- | --------------------------------- |
| `JPShippingTypeShipping`      | Shipping.<br />The default value. |
| `JPShippingTypeDelivery`      | Delivery.                         |
| `JPShippingTypeStorePickup`   | Store Pickup.                     |
| `JPShippingTypeServicePickup` | Service Pickup.                   |

Setting the shipping methods requires an array of **PaymentShippingMethod** objects.

To set an array of **paymentShippingMethod&#x20;**&#x6F;bjects:

:::BlockQuote
NSDecimalNumber \*deliveryCost = \[NSDecimalNumber decimalNumberWithString:@"25.0"];

PaymentShippingMethod \*delivery;
delivery = \[\[PaymentShippingMethod alloc] initWithIdentifier:@"delivery"&#x20;
detail:@"Deliver to your address"&#x20;
label:@"Delivery"&#x20;
amount\:deliveryCost];
applePayConfig.shippingMethods = @\[delivery];
:::

***

**Getting the Billing and Shipping Details**

To get the billing and shipping information back from the consumer:

Set the **returnedContactInfo**:

:::BlockQuote
applePayConfig.returnedContactInfo = ReturnedInfoBillingContacts;
:::

| **Parameter**                    | **Description**                                   |
| -------------------------------- | ------------------------------------------------- |
| `JPReturnedInfoBillingContacts`  | Billing details returned.<br />The default value. |
| `JPReturnedInfoShippingContacts` | Shipping details returned.                        |
| `JPReturnedInfoAll`              | Billing and Shipping details returned.            |
::::

***

## Going Live with iOS

### Point to the Live Environment

1. In **ViewController** delete the line that specifies the targeted environment: `judo.sandboxed = YES;`
2. Replace your sandbox API Token and Secret for the **live&#x20;**&#x41;PI Token and Secret.&#x20;
   Find these in **Judopay Portal&#x20;**> **Your apps&#x20;**> \{**app name**} > **Live Tokens**

***

### Test live payments

:::hint{type="info"}
Use the live environment for testing before deploying your app.
:::

- Ensure the SDK is properly configured for the live environment
  - Use real debit or credit cards
    - Test cards provided will not work in live
    - We recommend to perform pre-authorizations followed by a void, or regular payments followed by a refund&#x20;
  - Send a refund through the **JudopayPortal** > **History**
- Test all payment scenarios and security features to verify the expected behaviour

Follow our suggested guidelines to simulate both positive / happy path scenarios, and negative scenarios in the sandbox environment to test your integration is working correctly.
This will give you confidence for when your integration goes live.

See:

- [Testing iOS SDK - Card Payments](docId:9t9c80aDjPMu0BaiyS7SK)
- [Testing Apple Pay™ Wallet - via Mobile SDK](docId\:hYAnZIM115Id6daBs-bkP)

