Using iOS SDK
To use Apple Pay for doing payments, the merchant needs to create an Apple Pay button and then tokenize the payment on tap.
Enable ApplePay capability
Enable Apple Pay in your app by adding its capability.
- In Xcode, open your project settings, go to the Signing and Capabilities tab, and add the Apple Pay capability.
- You might be asked to log into your developer account at this stage. Then, select the merchant ID you created earlier, and your app will be set up to accept Apple Pay.
Check this page about setting up the merchant ID: Apple Pay integration - Overview - Payment Hub API - Paysafe Confluence
Swift Package Manager
- In Xcode, select File > Add Packages… and enter https://github.com/paysafegroup/paysafe_sdk_ios_payments_api as the repository URL and select the latest version number.
- Tick the checkboxes for the specific Paysafe libraries you wish to include. In this case, PaysafeApplePay.
- If you look at your app target, you will see that the Paysafe libraries you chose are automatically linked as a frameworks to your app (see General > Frameworks, Libraries, and Embedded Content).
// In your Swift file
import PaysafeApplePay
Cocoapods
// Add in your Podfile
pod 'PaysafePaymentsSDK'
// Or you can import only a single module
pod 'PaysafePaymentsSDK/PaysafeApplePay'
// In your Swift file
import PaysafePaymentsSDK
Setup 
After Paysafe iOS package is integrated into your project, setup PaysafeSDK on application start.
import PaysafeApplePay
PaysafeSDK.shared.setup(
apiKey: apiKey,
environment: .test
)
{ result in
switch result {
case .success:
print("[Paysafe SDK] initialized successfully")
case let .failure(error):
print("[Paysafe SDK] initialize failure \(error.displayMessage)")
}
}
The setup function creates and initializes the Paysafe iOS SDK. Pass the following parameters during its initialization from the application:
Parameter
| Required
| Type
| Description
|
---|---|---|---|
apiKey | true | String | The Base64-encoded version of the single-use token API key is used to authenticate with the Payment Hub REST API. |
environment | true | PaysafeEnvironment | PaysafeEnvironment is an enum type with the following cases:
|
theme | false | PSTheme | This parameter is specific for Card Payments. If theme parameter is not provided, then the default theme is applied. |
API Key
The Base64-encoded version of the single-use token API key is used to authenticate with the Payment Hub REST API. Please refer “Before You Being” on how to obtain the API Keys
Note that this key can be used only to generate single-use tokens for use with the Payments API and has no other API access rights (such as for taking payments). Consequently, it can be exposed publicly in the user's browser.
Environment
The environment string is used to select the environment to use for tokenization. The accepted environments are LIVE (the Paysafe Production environment) and TEST (the Paysafe Merchant Test or Sandbox environment).
Do not use real card numbers or other payment instrument details in the Merchant Test environment. It is not compliant with Payment Card Industry Data Security Standards (PCI-DSS) and does not protect cardholder/payee information. Any upload of real cardholder data is strictly prohibited, as described in the Terms of Use.
Callback error object
The following table describes the contents of the error object:
Parameter | Required | Type | Description |
code | true | String | Error code |
displayMessage | true | String | Error message for display to customers. |
detailedMessage | true | String | Detailed description of the error (this information should not be displayed to customers). |
correlationId | true | String | Unique error ID to be provided to Paysafe Support during investigation |
Setup errors
Error code
| Display message
| Detailed message
| Comments
|
---|---|---|---|
9167 | There was an error (9167), please contact our support. | The API key should not be empty. | |
9013 | There was an error (9013), please contact our support. | Invalid API key. | The decoded API key does not conform with the format "username:password". |
Initialize
To use the Apple Pay module, PSApplePayContext needs to be initialized.
The initialize() method signature is the following:
/// Initializes the PSApplePayContext.
///
/// - Parameters:
/// - currencyCode: Currency code
/// - accountId: Account id
/// - merchantIdentifier: Merchant identifier
/// - countryCode: Country code
/// - completion: PSApplePayContextInitializeBlock
public static func initialize(
currencyCode: String,
accountId: String,
merchantIdentifier: String,
countryCode: String,
completion: @escaping PSApplePayContextInitializeBlock
)
Parameter
| Required
| Type
| Description
|
---|---|---|---|
currencyCode | true | String | The currencyCode accepts 3 letter abbreviations of the ISO standard currencies. |
accountId | true | String | The id of the selected merchant account to use to process the payment. If you are a merchant, then this field is required only if you have more than one account configured for the same payment method and currency. If you are a partner using a shared API key, then this field is mandatory. |
merchantIdentifier | true | String | This value must match one of the merchant identifiers specified by the Merchant IDs Entitlement key in the app’s entitlements. |
countryCode | true | String | Set this property to the two-letter ISO 3166 code for the country or region of the merchant’s principle place of business. This is often the location for settling the payment. |
completion | true | PSApplePayContextInitializeBlock | This block is a type alias for a completion handler that receives as parameter a Result object. public typealias PSApplePayContextInitializeBlock = (Result<PSApplePayContext, PSError>) > Void The initialize method returns the a Result that represents either a PSApplePayContext instance when successful either an Error object. |
Usage example
PSApplePayContext.initialize(
currencyCode: "USD",
accountId: "<accountId>",
merchantIdentifier: "<your.merchant.identifier>",
countryCode: "US"
) { [weak self] result in
DispatchQueue.main.async { [weak self] in
guard let self else { return }
switch result {
case let .success(applePayContext):
self.applePayContext = applePayContext
case .failure:
break
}
}
}
Apple Pay button
Paysafe iOS SDK offers a convenience method to create an Apple Pay button for the merchants to integrate in their checkout screens.
The Apple Pay button can be added by using the following methods
/// Returns a `PSApplePayButtonSwiftUIView`
///
/// - Parameters:
/// - type: Apple Pay button type
/// - style: Apple Pay button style
/// - action: Apple Pay button action closure
public func applePaySwiftUIButton(
type: PSApplePayButtonView.ButtonType,
style: PSApplePayButtonView.ButtonStyle,
action: (() -> Void)?
) -> PSApplePayButtonSwiftUIView
/// Returns a `PSApplePayButtonView`
///
/// - Parameters:
/// - type: Apple Pay button type
/// - style: Apple Pay button style
/// - action: Apple Pay button action closure
public func applePayButton(
type: PSApplePayButtonView.ButtonType,
style: PSApplePayButtonView.ButtonStyle,
action: (() -> Void)?
) -> PSApplePayButtonView
The parameters are described below:
Parameter
| Required
| Type
| Description
|
---|---|---|---|
type | true | ButtonType | ButtonType is an enum type with the following cases:
|
style | true | ButtonStyle | ButtonStyle is an enum type with the following cases:
|
action | true | (() -> Void)? | ApplePay button tap action handler. |
Usage example
/// SwiftUI
applePayContext.applePaySwiftUIButton(
type: .buy,
style: .automatic
) {
// tap action handler
}
/// UIKit
let button = applePayContext.applePayButton(
type: .buy,
style: .automatic
) {
// tap action handler
}
Tokenization
This tokenize method returns a PaymentHandle result, which will resolve to a single-use payment handle representing the user's sensitive card data. This handle can be used by the Payments API to take payments. Single-use handles are valid for only 15 minutes and are not consumed by verification. See Pa yments with a Handle for more details.
Tokenize callback signature
The tokenize function has the following signature:
/// PaysafeCore ApplePay tokenize method.
///
/// - Parameters:
/// - options: PSApplePayTokenizeOptions
/// - completion: PSTokenizeBlock
public func tokenize(
using options: PSApplePayTokenizeOptions,
completion: @escaping PSTokenizeBlock
)
The tokenize() function provides a convenient method for tokenizing sensitive card data, allowing secure payment processing. Upon invocation, this function returns a completion handler that resolves to a single-use payment handle, which represents the user's sensitive card data. This handle can be utilized by the Payments API for payment transactions. It's important to note that single-use handles are valid for only 15 minutes and are not consumed during verification.
Parameters:
- options: An instance of PSApplePayTokenizeOptions containing various parameters for tokenization, such as the payment amount, transaction type, account ID and ApplePay configuration.
- completion: A completion handler of type PSTokenizeBlock, which is executed once the tokenization process is complete. The completion handler provides the single-use payment handle or any error encountered during the tokenization process.
PSApplePayTokenizeOptions
The PSApplePayTokenizeOptions structure provides a comprehensive set of options for configuring the tokenization process. These options include:
The PSApplePayTokenizeOptions structure provides a comprehensive set of options for configuring the tokenization process. These options include:
Parameter
| Required
| Type
| Description
|
---|---|---|---|
amount | true | Double | The payment amount is in minor units to charge the customer's card. Use the correct minor units amount for the merchant account currency. For example, to process US $10.99, this value should be 1099. To process 1000 Japanese Yen, this value should be 1000. To process 10.139 Tunisian dinar, this value should be 10139. Min = 1 Max = 999999999 When using 3DS 2 (i.e. useThreeDSecureVersion2= true), amount with value: "0" can be passed. |
currencyCode | true | String | The currencyCode accepts 3 letter abbreviations of the ISO standard currencies. |
accountId | true | String | The id of the selected merchant account to use to process the payment. If you are a merchant, then this field is required only if you have more than one account configured for the same payment method and currency. If you are a partner using a shared API key, then this field is mandatory. |
transactionType | true | TransactionType | This specifies the transaction type for which the Payment Handle is created. Possible values are:
|
merchantRefNum | true | String | A unique identifier is provided by the merchant for every transaction in Paysafe iOS SDK. |
billingDetails | false | BillingDetails | Card billing address - additional details for the billingDetails object can be found in the Payments API documentation. |
profile | false | Profile | This is the profile of the customer - additional details for the profile object can be found in the Payments API documentation. |
merchantDescriptor | false | MerchantDescriptor | This is a merchant descriptor that is displayed on a customer’s card statement. |
shippingDetails | false | ShippingDetails | This is the shipping usage information. |
psApplePay | true | ApplePay bottom sheet configuration.
| |
PSApplePayItem | |||
label | true | String | Payment item label |
Usage example
let completion: PSTokenizeBlock = { [weak self] tokenizeResult in
DispatchQueue.main.async { [weak self] in
guard let self else { return }
switch tokenizeResult {
case let .success(paymentHandleResponse):
/// handle paymentHandleResponse
case let .failure(error):
alertTexts = ("Error", "\(error.localizedDescription)")
presentAlert = true
}
}
}
/// Payment amount in minor units
let amount = totalPrice * 100
let options = PSApplePayTokenizeOptions(
amount: amount,
merchantRefNum: "<merchant-ref-num>",
accountId: "<account-id>",
currencyCode: "USD",
paymentItem: PSApplePayItem(
label: "Demo iOS"
)
)
applePayContext.tokenize(
using: options,
completion: completion
)
Apple Pay exceptions
Error code
| Display message
| Detailed message
| Comments
|
---|---|---|---|
9061 | There was an error (9061), please contact our support. | Invalid account id for ${paymentMethod} | AccountId is present, but is not configured for the wanted payment context. |
9042 | There was an error (9042), please contact our support. | User aborted authentication | Whenever is prompted to authenticate to use PayPal/ApplePay/GooglePay, but the user has cancelled the authentication with the payment method provider. |
9054 | There was an error (9054), please contact our support. | Amount should be a number greater than 0 no longer than 11 characters | The amount value should be a positive number. |
9136 | There was an error (9136), please contact our support. | Tokenization is already in progress. | Whenever merchant calls tokenize before the previous one has completed |