Search Overlay

Tokenize

The tokenize method returns a PaymentHandle result, which will resolve to a single-use payment handle representing the customer's sensitive card data. The payment handle can be used by the Payments API to take payments. Single-use handles are valid for only 5 minutes and are not consumed by verification. See Payments with a Handle for more details.

The tokenize function has the following signatures:

Tokenize callback signature

/// This tokenize function returns a completion, 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.
///
/// - Note: PSTokenizeOptions
/// * amount: Payment amount in minor units
/// * transactionType: Transaction type
/// * paymentType: Payment type
/// * merchantRefNum: Merchant reference number
/// * customerDetails: Customer details
/// * merchantDescriptor: Merchant descriptor
/// * accountId: Account id
/// * threeDS: ThreeDS
/// * applePay: Apple Pay additional data
/// * singleUseCustomerToken: Single use customer token
/// * paymentTokenFrom: Payment token from
/// - Parameters:
/// - options: PSTokenizeOptions
/// - completion: PSTokenizeBlock

public func tokenize(
using options: PSTokenizeOptions,
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 PSCardTokenizeOptions containing various parameters for tokenization, such as the payment amount, transaction type, payment type, merchant reference number, customer details, merchant descriptor, account ID, ThreeDS information, and single-use customer token.
  • 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.

PSTokenizeOptions

The PSTokenizeOptions 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:

  • payment - Payment Handle is created to continue the Payment.
  • standaloneCredit - Payment Handle is created to continue the standalone credit.
  • originalCredit - Payment Handle is created to continue the original credit.
  • verification - Payment Handle is created to continue the verification request.

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.

singleUseCustomerToken

false

String

This is the singleUseCustomerToken that the merchant generated using the Create a Single-Use Customer Token request.

Specify this parameter when you want to use a saved card.

paymentTokenFrom

false

String

This is single-use payment handle associated with the customer.

Specify this parameter when you want to use a saved card.

renderType

false

RenderType

Specify the render type that the device supports for displaying specific challenge user interfaces within the SDK.

The list of all the render types:

  • native
  • html
  • both

threeDS

false

ThreeDS

An object representing the 3DS parameters. Include this object to enable 3DS.

simulator false SimulatorType

The simulator is only applicable in the test environment and its default value is set as internalSimulator.
In the production environment, the simulator value is disregarded, even if provided, and the experience will be the same as if the simulator value were set as externalSimulator.

SimulatorType is an enum type with the following cases:

  • .internalSimulator
  • .externalSimulator

If omitted, defaults to .externalSimulator. 

BillingDetails

country

true

String

Country of billing address

zip

true

String

Zip code of the address

state

false

String

State/province/region of the address

city

false

String

City in which the address is located

street

false

String

The first line of the street address

street2

false

String

The second line of the street address

phone

false

String

The phone number of the customer

nickname

false

String

The nickname of the customer

Profile

firstName

false

String

This is the customer’s first name.

lastName

false

String

This is the customer’s last name.

email

false

String

This is the customer’s email address.

phone

false

String

This is the customer’s phone number.

cellPhone

false

String

This is the customer’s cell phone number.

MerchantDescriptor

dynamicDescriptor

true

String

This is a merchant descriptor that is displayed on a customer’s card statement

phone

false

String

This is the merchant’s phone number, which is appended to the merchant descriptor on a customer’s card statement.

ShippingDetails

shipMethod

false

String

 

country

true

String

Country of shipping address

zip

true

String

Zip code of the shippingaddress

state

false

String

State/province/region of the shippingaddress

city

false

String

City in which the shippingaddress is located

street

false

String

The first line of the street shippingaddress

street2

false

String

The second line of the street shippingaddress

ThreeDs

deviceChannel

true

string

This is the type of channel interface used to initiate the transaction. Possible values are:

  • BROWSER
  • SDK
  • 3RI

merchantUrl

true

String

This is the fully qualified URL of the merchant's commercial or customer care website.

useThreeDSecureVersion2

false

Bool

Specifies whether this instance of Paysafe.js should implement 3DS 2. If true and accountId is not configured for 3DS 2, an error will be returned in the callback.

If omitted, defaults to false.

authenticationPurpose

true

AuthenticationPurpose

Indicates the type of Authentication request. This data element provides additional information to the ACS to determine the best approach for handing an authentication request.

AuthenticationPurpose is an enum type with the following cases:

  • .paymentTransaction
  • .recurringTransaction
  • .addCard
  • .maintainCard
  • .emvTokenVerification
  • .instalmentTransaction

If omitted, defaults to .paymentTransaction

process

false

Bool

 

maxAuthorizationsForInstalmentPayment

false

Int

Indicates the maximum number of authorizations permitted for installment payments.

Min = 1

Max = 999

Required when authenticationPurpose is set to .instalmentTransaction.

PSTokenizeBlock

The completion handler type PSTokenizeBlock is defined as follows:

public typealias PSTokenizeBlock = (Result<String, PSError>) -> Void.

It indicates that the completion handler receives a Result type with a string representing the single-use payment handle in case of success, or a PSError in case of failure.

Tokenization example

/// Payment amount in minor units
let amount = totalPrice * 100
let options = PSCardTokenizeOptions(
amount: amount,
currencyCode: "USD",
transactionType: .payment,
merchantRefNum: "<merchant-ref-num>",
billingDetails: BillingDetails(
country: country,
zip: "1234567",
state: "State",
city: "City",
street: "Good Street 123",
nickName: "nickName"
),
profile: Profile(
firstName: "John",
lastName: "Doe"
),
accountId: "<accountId>"
)

cardForm.tokenize(using: options) { [weak self] tokenizeResult in
DispatchQueue.main.async { [weak self] in
guard let self else { return }
isloading = false
switch tokenizeResult {
case let .success(paymentHandleToken):
print("Success. Payment handle token: \(paymentHandleToken)")
case let .failure(error):
print("Error", "\(error.displayMessage)")
}
}
}

Tokenization with 3D Secure

3D Secure 2 provides an improved, seamless way to authenticate customers while adding support for mobile applications and for biometric and token validation, and streamlining the checkout experience using “frictionless” authentication. See the 3D Secure 2 documentation for full details on implementing 3D Secure 2.

The merchant must first be configured by Paysafe Group in order to use 3D Secure 2. 3D Secure 2 is supported only for Visa, Mastercard, and American Express.

With 3D Secure 2, the merchant can pass in some additional optional parameters in the threeDS object for Paysafe iOS SDK:

  • authenticationPurpose – Only two values are permitted: .paymentTransaction (default value) and
  • .instalmentTransaction for maxAuthorizationsForInstalmentPayment parameter
  • billingCycle

The card holderName parameter is mandatory in order to use 3D Secure 2.

See the authentications object in the 3D Secure 2 API documentation for a description of these parameters. Note:
For 3D Secure enrolled cards, the customer may be shown an overlay window from their card issuer to authorize the payment. 3D Secure 2 is supported only for Visa, Mastercard, and American Express. 

/// Payment amount in minor units
let amount = totalPrice * 100
let options = PSTokenizeOptions(
amount: amount,
currencyCode: "USD",
transactionType: .payment,
merchantRefNum: "<merchant-ref-num>",
billingDetails: BillingDetails(
country: country,
zip: "1234567",
state: "State",
city: "City",
street: "Good Street 123",
nickName: "nickName"
),
profile: Profile(
firstName: "John",
lastName: "Doe"
),
accountId: "<accountId>",
threeDs: ThreeDS(
merchantUrl: "https://api.qa.paysafe.com/checkout/v2/index.html#/desktop",
authenticationPurpose: .paymentTransaction,
maxAuthorizationsForInstalmentPayment: 2,
electronicDelivery: ElectronicDelivery(
isElectronicDelivery: true,
email: "example@example.com"
), messageCategory: .payment,
requestorChallengePreference: .noPreference,
userLogin: UserLogin(
data: "Some up to 2048 bytes undefined data",
authenticationMethod: .noLogin,
time: "2014-01-26T10:32:28Z"
),
transactionIntent: .goodsOrServicePurchase,
initialPurchaseTime: "2014-01-26T10:32:28Z",
orderItemDetails: OrderItemDetails(
preOrderItemAvailabilityDate: "2014-01-26",
preOrderPurchaseIndicator: "MERCHANDISE_AVAILABLE",
reorderItemsIndicator: "FIRST_TIME_ORDER",
shippingIndicator: "SHIP_TO_BILLING_ADDRESS"
),
purchasedGiftCardDetails: PurchasedGiftCardDetails(
amount: 1234,
count: 2,
currency: "ARS"
),
priorThreeDSAuthentication: PriorThreeDSAuthentication(
data: "Some up to 2048 bytes undefined data",
method: .frictionlessAuthentication,
id: "123e4567-e89b-12d3-a456-426655440001",
time: "2014-01-26T10:32:28Z"
),
shippingDetailsUsage: ShippingDetailsUsage(
cardHolderNameMatch: true,
initialUsageDate: "2014-01-26",
initialUsageRange: .currentTransaction
),
suspiciousAccountActivity: true,
totalPurchasesSixMonthCount: 1,
transactionCountForPreviousDay: 1,
transactionCountForPreviousYear: 3,
travelDetails: TravelDetails(
isAirTravel: true,
airlineCarrier: "Windsor",
departureDate: "2014-01-26",
destination: "SOF",
origin: "BCN",
passengerFirstName: "John",
passengerLastName: "Smith"
)
)
)

cardForm.tokenize(using: options) { [weak self] tokenizeResult in
DispatchQueue.main.async { [weak self] in
guard let self else { return }
switch tokenizeResult {
case let .success(paymentHandleToken):
print("Success. Payment handle token: \(paymentHandleToken)")
case let .failure(error):
print("Error", "\(error.displayMessage)")
}
}
}

Tokenization exceptions

Error code Display message Detailed message Comments

9003

There was an error (9003), please contact our support.

Invalid ${field} field value(s).

*added "field" word, *added "value(s)" instead of "value"

 

Thrown when merchant skips field validations and tries to tokenize invalid using fields.

 

Important:

This exception is thrown also when the backend request fails with

  • HTTP 400
  • the error code in the response is either 7508 or 5068

 

5068 - Either you submitted a request that is missing a mandatory field or the value of a field does not match the format expected.

7508 - You submitted an invalid card number or brand or combination of card number and brand with your request.

 

9125

There was an error (9125), please contact our support.

Unsupported card brand used

 

9040

There was an error (9040), please contact our support.

Authentication result is not accepted for the provided account

  • When the challenge when is not successful.
  • When the result for the authentication call from 3DS after Cardinal is not successful.

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

9098

There was an error (9098), please contact our support.

Invalid parameter in merchantDescriptor.dynamicDescriptor

String value should have <= 20 characters.

9099

There was an error (9099), please contact our support.

Invalid parameter in merchantDescriptor.phone

String value should have <= 13 characters.

9112

There was an error (9112), please contact our support.

Profile firstName should be valid

String value should have <= 80 characters.

9113

There was an error (9113), please contact our support.

Profile lastName should be valid

String value should have <= 80 characters.

9119

There was an error (9119), please contact our support.

Profile email should be valid

Use the following regex to check:
^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$