### Install Dependencies
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Install necessary Ruby gems and CocoaPods dependencies to build and run the example app.
```shell
gem install bundler
bundle
pod install
```
--------------------------------
### Clone the Repository
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Clone the YooKassa Payments Swift SDK repository from GitHub to get started.
```shell
git clone https://github.com/yoomoney/yookassa-payments-swift.git
```
--------------------------------
### Initialize and Present Payment UI
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Use `TokenizationAssembly.makeModule` to create a payment view controller. Configure `TokenizationModuleInputData` with your application's details, payment settings, and customization options. Present the view controller to start the payment flow.
```swift
import YooKassaPayments
class CheckoutViewController: UIViewController {
// Retain the module so you can call startConfirmationProcess later
private var tokenizationViewController: (UIViewController & TokenizationModuleInput)?
func startPayment() {
let amount = Amount(value: 1_499.00, currency: .rub)
let inputData = TokenizationModuleInputData(
clientApplicationKey: "live_XXXXXXXXXXXXXXXXXXXXXXXX",
shopName: "My Store",
purchaseDescription: "Order #42 — 3 items",
amount: amount,
tokenizationSettings: TokenizationSettings(
paymentMethodTypes: [.bankCard, .yooMoney, .sberbank, .applePay],
showYooKassaLogo: true
),
applePayMerchantIdentifier: "merchant.com.mystore",
isLoggingEnabled: false,
customizationSettings: CustomizationSettings(mainScheme: .systemBlue),
savePaymentMethod: .userSelects,
moneyAuthClientId: "yoomoney_oauth_client_id",
applicationScheme: "myapp://",
customerId: "user-email@example.com"
)
let flow: TokenizationFlow = .tokenization(inputData)
let vc = TokenizationAssembly.makeModule(inputData: flow, moduleOutput: self)
tokenizationViewController = vc
present(vc, animated: true)
}
}
```
--------------------------------
### Start Card.io Scanning with CardIOView
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/CardIO/CardIO/README.md
Create and add a CardIOView to your view hierarchy to initiate card scanning. Set the delegate to receive scan results. Ensure the view is initialized with an appropriate frame.
```Objective-C
// SomeViewController.m
- (IBAction)scanCard:(id)sender {
CardIOView *cardIOView = [[CardIOView alloc] initWithFrame:CGRECT_WITHIN_YOUR_VIEW];
cardIOView.delegate = self;
[self.view addSubview:cardIOView];
}
```
--------------------------------
### Install CocoaPods
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Installs or updates CocoaPods to version 1.10.0 or higher. Ensure you have Ruby installed.
```zsh
gem install cocoapods
```
--------------------------------
### Start Card.io Scanning with Payment View Controller
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/CardIO/CardIO/README.md
Initiate the card scanning process by presenting a CardIOPaymentViewController. Ensure your view controller conforms to CardIOPaymentViewControllerDelegate to receive the results.
```Objective-C
// SomeViewController.m
- (IBAction)scanCard:(id)sender {
CardIOPaymentViewController *scanViewController = [[CardIOPaymentViewController alloc] initWithPaymentDelegate:self];
[self presentViewController:scanViewController animated:YES completion:nil];
}
```
--------------------------------
### Start Payment Confirmation
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Initiate the payment confirmation process by calling this method with the provided confirmation URL and payment method type, typically when the server indicates a 'pending' payment status.
```swift
self.tokenizationViewController.startConfirmationProcess(
confirmationUrl: confirmationUrl,
paymentMethodType: paymentMethodType
)
```
--------------------------------
### CocoaPods Integration for card.io
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/CardIO/CardIO/README.md
Add this line to your Podfile to integrate the card.io SDK using CocoaPods. Ensure you run 'pod install' afterwards.
```ruby
pod 'CardIO'
```
--------------------------------
### Start Payment Confirmation Process in Swift
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Call this method on the retained tokenization view controller when your backend reports a `pending` payment requiring user confirmation. Do not dismiss the SDK before calling this method.
```swift
// After receiving a pending payment from your backend:
tokenizationViewController?.startConfirmationProcess(
confirmationUrl: "https://3ds.yookassa.ru/api/v2/3d-secure/..",
paymentMethodType: .bankCard // or .sberbank
)
// SDK handles the WebView / app-switch internally.
// didSuccessfullyConfirmation(paymentMethodType:) fires on success.
```
--------------------------------
### Install YooKassa Payments SDK via CocoaPods
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Add the SDK to your Podfile, specifying the repository and a release tag. Ensure you are using Swift 5.0+ and iOS 10.0+.
```ruby
source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/yoomoney-tech/cocoa-pod-specs.git'
platform :ios, '10.0'
use_frameworks!
target 'MyApp' do
pod 'YooKassaPayments',
:git => 'https://github.com/yoomoney/yookassa-payments-swift.git',
:tag => '6.7.0'
end
```
--------------------------------
### Start Card Scanning
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/CardIO/CardIO/README.md
Implement an IBAction to make the hidden CardIOView visible, initiating the card scanning process when a user action occurs.
```Objective-C
// SomeViewController.m
- (IBAction)scanCard:(id)sender {
self.cardIOView.hidden = NO;
}
```
--------------------------------
### Handle Card Scanning Data with CardIO
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Extend your `CardScannerProvider` to conform to `CardIOPaymentViewControllerDelegate` for receiving scanned card information. This example shows how to process card details or cancellation events.
```swift
extension CardScannerProvider: CardIOPaymentViewControllerDelegate {
public func userDidProvide(_ cardInfo: CardIOCreditCardInfo!,
in paymentViewController: CardIOPaymentViewController!) {
let scannedCardInfo = ScannedCardInfo(number: cardInfo.cardNumber,
expiryMonth: "\(cardInfo.expiryMonth)",
expiryYear: "\(cardInfo.expiryYear)")
cardScanningDelegate?.cardScannerDidFinish(scannedCardInfo)
}
public func userDidCancel(_ paymentViewController: CardIOPaymentViewController!) {
cardScanningDelegate?.cardScannerDidFinish(nil)
}
}
```
--------------------------------
### Present Tokenization ViewController
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Instantiate the ViewController using TokenizationAssembly and present it to initiate the payment process. Ensure you provide an object conforming to TokenizationModuleOutput.
```swift
let viewController = TokenizationAssembly.makeModule(inputData: inputData,
moduleOutput: self)
present(viewController, animated: true, completion: nil)
```
--------------------------------
### Configure Info.plist for YooMoney Schemes
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Add `LSApplicationQueriesSchemes` and `CFBundleURLTypes` to your `Info.plist` to allow the SDK to interact with the YooMoney app and handle callback URLs.
```plist
LSApplicationQueriesSchemes
yoomoneyauth
CFBundleURLTypes
CFBundleTypeRole
Editor
CFBundleURLName
${BUNDLE_ID}
CFBundleURLSchemes
examplescheme
```
--------------------------------
### Configure Test Mode Settings
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Create a `TestModeSettings` object to configure the SDK for test mode. This allows emulating server responses without making actual network requests.
```swift
let testModeSettings = TestModeSettings(paymentAuthorizationPassed: false,
cardsCount: 2,
charge: Amount(value: 999, currency: .rub),
enablePaymentError: false)
```
--------------------------------
### Configure Standard Checkout with TokenizationModuleInputData
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Use `TokenizationModuleInputData` to set up the standard checkout flow. Required parameters include client key, shop name, purchase description, amount, and save payment method preference. Optional parameters allow for gateway IDs, tokenization settings, card scanning, Apple Pay identifiers, return URLs, logging, customization, and customer IDs.
```swift
let inputData = TokenizationModuleInputData(
clientApplicationKey: "live_XXXXXXXXXXXXXXXX", // from YooMoney Merchant Profile
shopName: "Space Objects",
purchaseDescription: "An extra bright comet, rotation period: 112 years",
amount: Amount(value: 999.99, currency: .rub),
gatewayId: nil, // multi-gateway accounts only
tokenizationSettings: TokenizationSettings(
paymentMethodTypes: [.bankCard, .yooMoney],
showYooKassaLogo: true
),
testModeSettings: nil,
cardScanning: CardScannerProvider(), // optional card-scan integration
applePayMerchantIdentifier: "merchant.com.example",
returnUrl: nil, // only for custom 3DS handling
isLoggingEnabled: true,
userPhoneNumber: "+79001234567",
customizationSettings: CustomizationSettings(mainScheme: UIColor(red: 0.2, green: 0.5, blue: 1, alpha: 1)),
savePaymentMethod: .userSelects,
moneyAuthClientId: "yoomoney_client_id",
applicationScheme: "myapp://",
customerId: "user-42" // links saved methods to this user
)
```
--------------------------------
### Initialize Tokenization Module with Test Mode
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Pass the configured `TestModeSettings` object to the `testModeSettings` parameter when creating `TokenizationModuleInputData` to launch the SDK in test mode.
```swift
let moduleData = TokenizationModuleInputData(
...
testModeSettings: testModeSettings)
```
--------------------------------
### Create TokenizationModuleInputData
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Initialize TokenizationModuleInputData with your client application key, shop details, payment amount, and currency. Configure save payment method behavior.
```swift
let clientApplicationKey = ""
let amount = Amount(value: 999.99, currency: .rub)
let tokenizationModuleInputData =
TokenizationModuleInputData(clientApplicationKey: clientApplicationKey,
shopName: "Space objects",
purchaseDescription: """
An extra bright comet, rotation period: 112 years
""",
amount: amount,
savePaymentMethod: .on)
```
--------------------------------
### startConfirmationProcess
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Called on the retained tokenization view controller when your backend reports a `pending` payment that requires user confirmation (3-D Secure or SberPay redirect). Do **not** dismiss the SDK before calling this method.
```APIDOC
## `TokenizationModuleInput.startConfirmationProcess(confirmationUrl:paymentMethodType:)`
Called on the retained tokenization view controller when your backend reports a `pending` payment that requires user confirmation (3-D Secure or SberPay redirect). Do **not** dismiss the SDK before calling this method.
```swift
// After receiving a pending payment from your backend:
tokenizationViewController?.startConfirmationProcess(
confirmationUrl: "https://3ds.yookassa.ru/api/v2/3d-secure/",
paymentMethodType: .bankCard // or .sberbank
)
// SDK handles the WebView / app-switch internally.
// didSuccessfullyConfirmation(paymentMethodType:) fires on success.
```
```
--------------------------------
### Configure Info.plist for Deep Linking
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Add required `Info.plist` entries for SberPay and YooMoney mobile-app authorization to handle deep links correctly.
```xml
LSApplicationQueriesSchemes
sberpay
yoomoneyauth
CFBundleURLTypes
CFBundleTypeRoleEditor
CFBundleURLName$(BUNDLE_ID)
CFBundleURLSchemes
myapp
```
--------------------------------
### Import YooKassaPayments SDK
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Import the necessary SDK module at the beginning of your file to use YooKassaPayments entities.
```swift
import YooKassaPayments
```
--------------------------------
### Create TokenizationFlow
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Create a TokenizationFlow instance with the .tokenization case, passing the prepared TokenizationModuleInputData.
```swift
let inputData: TokenizationFlow = .tokenization(tokenizationModuleInputData)
```
--------------------------------
### Handle Tokenization Callback
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Implement the callback to receive payment tokens and send them to your server for processing. Do not close the module until the server confirms successful payment.
```swift
func tokenizationModule(_ module: TokenizationModuleInput,
didTokenize token: Tokens,
paymentMethodType: PaymentMethodType) {
// Send the token to your server.
}
```
--------------------------------
### Implement TokenizationModuleOutput Protocol in Swift
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Implement this delegate protocol to receive SDK events like successful tokenization, user cancellation, errors, and post-confirmation success. Handle the payment token by sending it to your backend.
```swift
extension CheckoutViewController: TokenizationModuleOutput {
// Called when the SDK has successfully produced a payment token
func tokenizationModule(
_ module: TokenizationModuleInput,
didTokenize token: Tokens,
paymentMethodType: PaymentMethodType
) {
// token.paymentToken is the one-time payment token
// Send it to your backend together with paymentMethodType
MyBackend.createPayment(
paymentToken: token.paymentToken,
paymentMethod: paymentMethodType
) { [weak self] result in
switch result {
case .success(let payment) where payment.status == "pending":
// Payment needs confirmation (3DS or SberPay)
DispatchQueue.main.async {
self?.tokenizationViewController?.startConfirmationProcess(
confirmationUrl: payment.confirmationUrl,
paymentMethodType: paymentMethodType
)
}
case .success:
DispatchQueue.main.async { self?.dismiss(animated: true) }
case .failure(let error):
print("Backend error:", error)
}
}
}
// Called when confirmation (3DS / SberPay) succeeds
func didSuccessfullyConfirmation(paymentMethodType: PaymentMethodType) {
DispatchQueue.main.async { [weak self] in
self?.dismiss(animated: true)
self?.showSuccessScreen(for: paymentMethodType)
}
}
// Called when the user closes the SDK without completing payment
func didFinish(on module: TokenizationModuleInput, with error: YooKassaPaymentsError?) {
DispatchQueue.main.async { [weak self] in
self?.dismiss(animated: true)
}
if let error = error {
switch error {
case .paymentMethodNotFound:
print("Saved payment method not found — show retry UI")
}
}
}
}
```
--------------------------------
### Configure Info.plist for SberPay URL Schemes
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Add `LSApplicationQueriesSchemes` and `CFBundleURLTypes` to your `Info.plist` to allow your app to be opened by SberPay and to define the custom URL scheme for returning to your app.
```plist
LSApplicationQueriesSchemes
sberpay
CFBundleURLTypes
CFBundleTypeRole
Editor
CFBundleURLName
${BUNDLE_ID}
CFBundleURLSchemes
examplescheme
```
--------------------------------
### Handle App URL Opening for YooMoney
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Implement `YKSdk.shared.handleOpen` in your `AppDelegate` to process URLs returned from the YooMoney mobile app after authorization.
```swift
func application(
_ application: UIApplication,
open url: URL,
sourceApplication: String?,
annotation: Any
) -> Bool {
return YKSdk.shared.handleOpen(
url: url,
sourceApplication: sourceApplication
)
}
```
```swift
@available(iOS 9.0, *)
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
return YKSdk.shared.handleOpen(
url: url,
sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String
)
}
```
--------------------------------
### Configure Payment Methods
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Customize the available payment methods by creating a PaymentMethodTypes OptionSet and inserting desired methods like .bankCard, .sberbank, .yooMoney, or .applePay.
```swift
// Create empty OptionSet PaymentMethodTypes
var paymentMethodTypes: PaymentMethodTypes = []
if {
// Adding the `.bankCard` element to paymentMethodTypes
paymentMethodTypes.insert(.bankCard)
}
if {
// Adding the `.sberbank` element to paymentMethodTypes
paymentMethodTypes.insert(.sberbank)
}
if {
// Adding the `.yooMoney` element to paymentMethodTypes
paymentMethodTypes.insert(.yooMoney)
}
if {
// Adding the `.applePay` element to paymentMethodTypes
paymentMethodTypes.insert(.applePay)
}
let tokenizationSettings = TokenizationSettings(paymentMethodTypes: paymentMethodTypes)
```
--------------------------------
### Configure Bank Card Payment Method
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Specify `.bankcard` in `paymentMethodTypes` when creating `TokenizationModuleInputData` to enable bank card payments.
```swift
let moduleData = TokenizationModuleInputData(
...,
paymentMethodTypes: [.bankCard])
```
--------------------------------
### Add YooKassaPayments Dependency to Podfile
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Specifies the YooKassaPayments SDK as a dependency in your Podfile. Replace 'tag' with the desired SDK version.
```shell
source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/yoomoney-tech/cocoa-pod-specs.git'
platform :ios, '10.0'
use_frameworks!
target 'Your Target Name' do
pod 'YooKassaPayments',
:git => 'https://github.com/yoomoney/yookassa-payments-swift.git',
:tag => 'tag'
end
```
--------------------------------
### TestModeSettings Configuration
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Configure `TestModeSettings` to enable offline testing. This allows simulation of wallet states and payment errors without making real network calls.
```APIDOC
## `TestModeSettings`
Enables offline test mode — no real network calls are made. Simulates a wallet with a configurable number of linked cards and can force a payment error.
```swift
let testSettings = TestModeSettings(
paymentAuthorizationPassed: false, // false = prompt for YooMoney auth in-flow
cardsCount: 3, // number of simulated linked cards
charge: Amount(value: 999, currency: .rub),
enablePaymentError: false // true = tokenization returns an error
)
let inputData = TokenizationModuleInputData(
clientApplicationKey: "test_XXXXXXXXXXXX",
shopName: "Test Store",
purchaseDescription: "Test purchase",
amount: Amount(value: 999, currency: .rub),
testModeSettings: testSettings,
savePaymentMethod: .off
)
```
```
--------------------------------
### Implement TokenizationModuleOutput Protocol
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Implement the TokenizationModuleOutput protocol to handle the results of the tokenization process, including successful tokenization, errors, and confirmation completion.
```swift
extension ViewController: TokenizationModuleOutput {
func tokenizationModule(
_ module: TokenizationModuleInput,
didTokenize token: Tokens,
paymentMethodType: PaymentMethodType
) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.dismiss(animated: true)
}
// Send the token to your system
}
func didFinish(
on module: TokenizationModuleInput,
with error: YooKassaPaymentsError?
) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.dismiss(animated: true)
}
}
func didSuccessfullyConfirmation(
paymentMethodType: PaymentMethodType
) {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
// Create a success screen after confirmation is completed (3DS or SberPay)
self.dismiss(animated: true)
// Display the success screen
}
}
}
```
--------------------------------
### Integrate Card Scanner into Tokenization
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Provide an instance of your `CardScannerProvider` to the `TokenizationModuleInputData` when initializing the tokenization module. This connects your card scanning implementation to the payment flow.
```swift
let inputData = TokenizationModuleInputData(
...
cardScanning: CardScannerProvider())
)
```
--------------------------------
### Configure YooMoney Payment Method
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Specify `.yooMoney` in `paymentMethodTypes` when creating `TokenizationModuleInputData` to enable YooMoney payments.
```swift
let moduleData = TokenizationModuleInputData(
...,
paymentMethodTypes: [.yooMoney])
```
--------------------------------
### TokenizationModuleInputData
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Primary configuration struct for the standard checkout flow. Requires clientApplicationKey, shopName, purchaseDescription, amount, and savePaymentMethod.
```APIDOC
## `TokenizationModuleInputData`
The primary configuration struct for the standard checkout flow. Required parameters are `clientApplicationKey`, `shopName`, `purchaseDescription`, `amount`, and `savePaymentMethod`.
```swift
let inputData = TokenizationModuleInputData(
clientApplicationKey: "live_XXXXXXXXXXXXXXXX", // from YooMoney Merchant Profile
shopName: "Space Objects",
purchaseDescription: "An extra bright comet, rotation period: 112 years",
amount: Amount(value: 999.99, currency: .rub),
gatewayId: nil, // multi-gateway accounts only
tokenizationSettings: TokenizationSettings(
paymentMethodTypes: [.bankCard, .yooMoney],
showYooKassaLogo: true
),
testModeSettings: nil,
cardScanning: CardScannerProvider(), // optional card-scan integration
applePayMerchantIdentifier: "merchant.com.example",
returnUrl: nil, // only for custom 3DS handling
isLoggingEnabled: true,
userPhoneNumber: "+79001234567",
customizationSettings: CustomizationSettings(mainScheme: UIColor(red: 0.2, green: 0.5, blue: 1, alpha: 1)),
savePaymentMethod: .userSelects,
moneyAuthClientId: "yoomoney_client_id",
applicationScheme: "myapp://",
customerId: "user-42" // links saved methods to this user
)
```
```
--------------------------------
### Configure Test Mode Settings
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Use `TestModeSettings` to enable offline testing without real network calls. Configure simulated cards, payment amounts, and error responses.
```swift
let testSettings = TestModeSettings(
paymentAuthorizationPassed: false, // false = prompt for YooMoney auth in-flow
cardsCount: 3, // number of simulated linked cards
charge: Amount(value: 999, currency: .rub),
enablePaymentError: false // true = tokenization returns an error
)
let inputData = TokenizationModuleInputData(
clientApplicationKey: "test_XXXXXXXXXXXX",
shopName: "Test Store",
purchaseDescription: "Test purchase",
amount: Amount(value: 999, currency: .rub),
testModeSettings: testSettings,
savePaymentMethod: .off
)
```
--------------------------------
### Create Bank Card Repeat Module Input Data
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Prepare the input data for repeating a bank card payment, including client key, shop name, purchase details, payment method ID, amount, and optional test mode and customization settings.
```swift
let bankCardRepeatModuleInputData = BankCardRepeatModuleInputData(
clientApplicationKey: oauthToken,
shopName: translate(Localized.name),
purchaseDescription: translate(Localized.description),
paymentMethodId: "24e4eca6-000f-5000-9000-10a7bb3cfdb2",
amount: amount,
testModeSettings: testSettings,
isLoggingEnabled: true,
customizationSettings: CustomizationSettings(mainScheme: .blueRibbon)
)
```
--------------------------------
### Configure Podfile for Static Linkage
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Configures the Podfile for static linkage and enables the `cocoapods-user-defined-build-types` plugin. Use this if you encounter issues with dynamic frameworks.
```shell
source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/yoomoney-tech/cocoa-pod-specs.git'
plugin 'cocoapods-user-defined-build-types'
enable_user_defined_build_types!
platform :ios, '10.0'
target 'Your Target Name' do
pod 'YooKassaPayments',
:build_type => :dynamic_framework,
:git => 'https://github.com/yoomoney/yookassa-payments-swift.git',
:tag => 'tag'
end
```
--------------------------------
### YKSdk.shared.handleOpen URL Handling
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Handle deep-link callbacks from SberPay or YooMoney mobile-app authorization by routing them back to the SDK using `YKSdk.shared.handleOpen`.
```APIDOC
## `YKSdk.shared.handleOpen(url:sourceApplication:)`
Routes deep-link callbacks back into the SDK after the user returns from SberPay (Sberbank Online app) or YooMoney mobile-app authorization.
```swift
// AppDelegate.swift
import YooKassaPayments
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// iOS 8 / iOS 9 legacy
func application(
_ application: UIApplication,
open url: URL,
sourceApplication: String?,
annotation: Any
) -> Bool {
return YKSdk.shared.handleOpen(url: url, sourceApplication: sourceApplication)
}
// iOS 9+
@available(iOS 9.0, *)
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
return YKSdk.shared.handleOpen(
url: url,
sourceApplication: options[.sourceApplication] as? String
)
}
}
```
Required `Info.plist` entries for SberPay + YooMoney mobile-app authorization:
```xml
LSApplicationQueriesSchemes
sberpay
yoomoneyauth
CFBundleURLTypes
CFBundleTypeRoleEditor
CFBundleURLName$(BUNDLE_ID)
CFBundleURLSchemes
myapp
```
```
--------------------------------
### Configure Customization Settings
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Customize the UI appearance by creating a `CustomizationSettings` object and passing it to the `customizationSettings` parameter of `TokenizationModuleInputData`. The `mainScheme` property controls the color of main elements.
```swift
let moduleData = TokenizationModuleInputData(
...
customizationSettings: CustomizationSettings(mainScheme: /* UIColor */ ))
```
--------------------------------
### Preload Card.io Scanning
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/CardIO/CardIO/README.md
Optionally call this method in viewWillAppear to speed up the subsequent launch of card.io scanning. This preloads necessary resources.
```Objective-C
// SomeViewController.m
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[CardIOUtilities preloadCardIO];
}
```
--------------------------------
### TokenizationAssembly.makeModule
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
The `TokenizationAssembly.makeModule` method is the primary factory for creating a payment UI view controller. It allows selection between standard multi-method checkout or saved-card repeat flows, and provides callbacks via a `moduleOutput` delegate.
```APIDOC
## TokenizationAssembly.makeModule(inputData:moduleOutput:)
### Description
This factory method creates a payment UI view controller for initiating payment flows. It accepts a `TokenizationFlow` enum to specify the checkout type (standard or saved-card repeat) and a `moduleOutput` delegate for handling callbacks.
### Method Signature
```swift
TokenizationAssembly.makeModule(inputData: TokenizationFlow, moduleOutput: TokenizationModuleOutput)
```
### Parameters
#### `inputData` (TokenizationFlow)
- **Type**: `TokenizationFlow` enum
- **Description**: Specifies the payment flow. Can be `.tokenization(TokenizationModuleInputData)` for standard checkout or `.tokenizationWithSavedCard(TokenizationModuleInputData)` for saved-card repeat.
#### `moduleOutput` (TokenizationModuleOutput)
- **Type**: `TokenizationModuleOutput` protocol
- **Description**: A delegate object that receives callbacks from the payment module.
### Usage Example
```swift
import YooKassaPayments
class CheckoutViewController: UIViewController, TokenizationModuleOutput {
private var tokenizationViewController: (UIViewController & TokenizationModuleInput)?
func startPayment() {
let amount = Amount(value: 1_499.00, currency: .rub)
let inputData = TokenizationModuleInputData(
clientApplicationKey: "live_XXXXXXXXXXXXXXXXXXXXXXXX",
shopName: "My Store",
purchaseDescription: "Order #42 — 3 items",
amount: amount,
tokenizationSettings: TokenizationSettings(
paymentMethodTypes: [.bankCard, .yooMoney, .sberbank, .applePay],
showYooKassaLogo: true
),
applePayMerchantIdentifier: "merchant.com.mystore",
isLoggingEnabled: false,
customizationSettings: CustomizationSettings(mainScheme: .systemBlue),
savePaymentMethod: .userSelects,
moneyAuthClientId: "yoomoney_oauth_client_id",
applicationScheme: "myapp://",
customerId: "user-email@example.com"
)
let flow: TokenizationFlow = .tokenization(inputData)
let vc = TokenizationAssembly.makeModule(inputData: flow, moduleOutput: self)
tokenizationViewController = vc
present(vc, animated: true)
}
// MARK: - TokenizationModuleOutput
func paymentAuthorizationFinished(with paymentToken: String) {
// Handle successful payment tokenization
print("Payment token: \(paymentToken)")
dismiss(animated: true)
}
func paymentAuthorizationFailed(with error: Error) {
// Handle payment authorization failure
print("Payment failed: \(error.localizedDescription)")
dismiss(animated: true)
}
}
```
```
--------------------------------
### Customize Tokenization Settings for Payment Methods and Logo
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Configure `TokenizationSettings` to control which payment methods are displayed and whether the YooKassa logo is shown. Use `.all` for all available methods or specify an array of `PaymentMethodType`.
```swift
// Show only bank cards and Apple Pay; hide the YooKassa logo
let settings = TokenizationSettings(
paymentMethodTypes: [.bankCard, .applePay],
showYooKassaLogo: false
)
// Show all available methods (default)
let allSettings = TokenizationSettings() // paymentMethodTypes: .all, showYooKassaLogo: true
// Use in TokenizationModuleInputData:
let inputData = TokenizationModuleInputData(
clientApplicationKey: "live_XXXX",
shopName: "Store",
purchaseDescription: "Order",
amount: Amount(value: 100, currency: .rub),
tokenizationSettings: settings,
savePaymentMethod: .off
)
```
--------------------------------
### Info.plist Camera Usage Description
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/CardIO/CardIO/README.md
Add the NSCameraUsageDescription key to your app's Info.plist file. This string will be displayed to the user when the app requests camera access for scanning.
```xml
Add the key [`NSCameraUsageDescription`](https://developer.library.prerelease/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW24) to your app's `Info.plist` and set the value to be a string describing why your app needs to use the camera (e.g. "To scan credit cards."). This string will be displayed when the app initially requests permission to access the camera.
```
--------------------------------
### Select TokenizationFlow in Swift
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Use this enum to select the SDK operating mode. Use `.tokenization` for a fresh checkout and `.bankCardRepeat` to charge a previously saved card by its stored `paymentMethodId`.
```swift
// Standard checkout (all payment methods)
let standardFlow: TokenizationFlow = .tokenization(
TokenizationModuleInputData(
clientApplicationKey: "live_XXXX",
shopName: "My Store",
purchaseDescription: "Subscription renewal",
amount: Amount(value: 299.00, currency: .rub),
savePaymentMethod: .on // force-save for recurring use
)
)
// Repeat charge on a previously saved card
let repeatFlow: TokenizationFlow = .bankCardRepeat(
BankCardRepeatModuleInputData(
clientApplicationKey: "live_XXXX",
shopName: "My Store",
purchaseDescription: "Monthly subscription",
paymentMethodId: "24e4eca6-000f-5000-9000-10a7bb3cfdb2",
amount: Amount(value: 299.00, currency: .rub),
savePaymentMethod: .on
)
)
let vc = TokenizationAssembly.makeModule(inputData: repeatFlow, moduleOutput: self)
present(vc, animated: true)
```
--------------------------------
### CardScanning Protocol Implementation
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Implement the `CardScanning` protocol to integrate a custom card-scanning library. The SDK will display your scanner when the user taps the scan button.
```APIDOC
## `CardScanning` Protocol
Plug in any card-scanning library (e.g., CardIO) by implementing `CardScanning`. The SDK will present your scanner view controller when the user taps the scan button.
```swift
import YooKassaPayments
import CardIO
final class CardScannerProvider: NSObject, CardScanning {
weak var cardScanningDelegate: CardScanningDelegate?
var cardScanningViewController: UIViewController? {
let vc = CardIOPaymentViewController(paymentDelegate: self)
return vc
}
}
extension CardScannerProvider: CardIOPaymentViewControllerDelegate {
func userDidProvide(
_ cardInfo: CardIOCreditCardInfo!,
in paymentViewController: CardIOPaymentViewController!
) {
let scanned = ScannedCardInfo(
number: cardInfo.cardNumber,
expiryMonth: "\(cardInfo.expiryMonth)",
expiryYear: "\(cardInfo.expiryYear)"
)
cardScanningDelegate?.cardScannerDidFinish(scanned)
}
func userDidCancel(_ paymentViewController: CardIOPaymentViewController!) {
cardScanningDelegate?.cardScannerDidFinish(nil)
}
}
// Pass the scanner when building input data:
let inputData = TokenizationModuleInputData(
clientApplicationKey: "live_XXXX",
shopName: "Store",
purchaseDescription: "Order",
amount: Amount(value: 100, currency: .rub),
cardScanning: CardScannerProvider(),
savePaymentMethod: .off
)
```
```
--------------------------------
### Present Tokenization View Controller for Bank Card Repeat
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Create and present the tokenization view controller using the `TokenizationAssembly` with the defined `TokenizationFlow` for bank card repeat payments.
```swift
let viewController = TokenizationAssembly.makeModule(
inputData: inputData,
moduleOutput: self
)
present(viewController, animated: true, completion: nil)
```
--------------------------------
### TokenizationModuleOutput Protocol
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
The delegate protocol for the host view controller to receive SDK events like successful tokenization, user cancellation, errors, and post-confirmation success.
```APIDOC
## `TokenizationModuleOutput` Protocol
The delegate protocol the host view controller must implement to receive SDK events: successful tokenization, user cancellation / errors, and post-confirmation success.
```swift
extension CheckoutViewController: TokenizationModuleOutput {
// Called when the SDK has successfully produced a payment token
func tokenizationModule(
_ module: TokenizationModuleInput,
didTokenize token: Tokens,
paymentMethodType: PaymentMethodType
) {
// token.paymentToken is the one-time payment token
// Send it to your backend together with paymentMethodType
MyBackend.createPayment(
paymentToken: token.paymentToken,
paymentMethod: paymentMethodType
) { [weak self] result in
switch result {
case .success(let payment) where payment.status == "pending":
// Payment needs confirmation (3DS or SberPay)
DispatchQueue.main.async {
self?.tokenizationViewController?.startConfirmationProcess(
confirmationUrl: payment.confirmationUrl,
paymentMethodType: paymentMethodType
)
}
case .success:
DispatchQueue.main.async { self?.dismiss(animated: true) }
case .failure(let error):
print("Backend error:", error)
}
}
}
// Called when confirmation (3DS / SberPay) succeeds
func didSuccessfullyConfirmation(paymentMethodType: PaymentMethodType) {
DispatchQueue.main.async { [weak self] in
self?.dismiss(animated: true)
self?.showSuccessScreen(for: paymentMethodType)
}
}
// Called when the user closes the SDK without completing payment
func didFinish(on module: TokenizationModuleInput, with error: YooKassaPaymentsError?) {
DispatchQueue.main.async { [weak self] in
self?.dismiss(animated: true)
}
if let error = error {
switch error {
case .paymentMethodNotFound:
print("Saved payment method not found — show retry UI")
}
}
}
}
```
```
--------------------------------
### Implement Card Scanning Protocol
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Implement the `CardScanning` protocol to integrate a third-party card scanner like CardIO. The SDK presents your scanner when the user taps the scan button.
```swift
import YooKassaPayments
import CardIO
final class CardScannerProvider: NSObject, CardScanning {
weak var cardScanningDelegate: CardScanningDelegate? // Required delegate
var cardScanningViewController: UIViewController? {
let vc = CardIOPaymentViewController(paymentDelegate: self)
return vc
}
}
extension CardScannerProvider: CardIOPaymentViewControllerDelegate {
func userDidProvide(
_ cardInfo: CardIOCreditCardInfo!,
in paymentViewController: CardIOPaymentViewController!
) {
let scanned = ScannedCardInfo(
number: cardInfo.cardNumber,
expiryMonth: "\(cardInfo.expiryMonth)",
expiryYear: "\(cardInfo.expiryYear)"
)
cardScanningDelegate?.cardScannerDidFinish(scanned)
}
func userDidCancel(_ paymentViewController: CardIOPaymentViewController!) {
cardScanningDelegate?.cardScannerDidFinish(nil)
}
}
// Pass the scanner when building input data:
let inputData = TokenizationModuleInputData(
clientApplicationKey: "live_XXXX",
shopName: "Store",
purchaseDescription: "Order",
amount: Amount(value: 100, currency: .rub),
cardScanning: CardScannerProvider(),
savePaymentMethod: .off
)
```
--------------------------------
### Implement Card Scanning Protocol
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Implement the `CardScanning` protocol to enable card scanning functionality. This involves creating an entity that conforms to the protocol and provides a `cardScanningViewController`.
```swift
class CardScannerProvider: CardScanning {
weak var cardScanningDelegate: CardScanningDelegate?
var cardScanningViewController: UIViewController? {
// Create and return scanner view controller
viewController.delegate = self
return viewController
}
}
```
--------------------------------
### Handle Deep Links in AppDelegate
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Route deep-link callbacks back into the SDK using `YKSdk.shared.handleOpen(url:sourceApplication:)` in your `AppDelegate`. This is crucial for returning users from SberPay or YooMoney mobile-app authorization.
```swift
// AppDelegate.swift
import YooKassaPayments
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// iOS 8 / iOS 9 legacy
func application(
_ application: UIApplication,
open url: URL,
sourceApplication: String?,
annotation: Any
) -> Bool {
return YKSdk.shared.handleOpen(url: url, sourceApplication: sourceApplication)
}
// iOS 9+
@available(iOS 9.0, *)
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
return YKSdk.shared.handleOpen(
url: url,
sourceApplication: options[.sourceApplication] as? String
)
}
}
```
--------------------------------
### Configure YooMoney Client ID
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Set the `moneyAuthClientId` parameter when initializing `TokenizationModuleInputData` with your YooMoney client ID.
```swift
let moduleData = TokenizationModuleInputData(
...
moneyAuthClientId: "client_id")
```
--------------------------------
### TokenizationFlow Enum
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Selects the SDK operating mode. Use `.tokenization` for a fresh checkout and `.bankCardRepeat` to charge a previously saved card by its stored `paymentMethodId`.
```APIDOC
## `TokenizationFlow` Enum
Selects the SDK operating mode. Use `.tokenization` for a fresh checkout and `.bankCardRepeat` to charge a previously saved card by its stored `paymentMethodId`.
```swift
// Standard checkout (all payment methods)
let standardFlow: TokenizationFlow = .tokenization(
TokenizationModuleInputData(
clientApplicationKey: "live_XXXX",
shopName: "My Store",
purchaseDescription: "Subscription renewal",
amount: Amount(value: 299.00, currency: .rub),
savePaymentMethod: .on // force-save for recurring use
)
)
// Repeat charge on a previously saved card
let repeatFlow: TokenizationFlow = .bankCardRepeat(
BankCardRepeatModuleInputData(
clientApplicationKey: "live_XXXX",
shopName: "My Store",
purchaseDescription: "Monthly subscription",
paymentMethodId: "24e4eca6-000f-5000-9000-10a7bb3cfdb2",
amount: Amount(value: 299.00, currency: .rub),
savePaymentMethod: .on
)
)
let vc = TokenizationAssembly.makeModule(inputData: repeatFlow, moduleOutput: self)
present(vc, animated: true)
```
```
--------------------------------
### Configure YooMoney Mobile App Authorization
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Provide the `applicationScheme` for returning to your app after YooMoney mobile app sign-in. This scheme must match the one configured in your app's `Info.plist`.
```swift
let moduleData = TokenizationModuleInputData(
...,
applicationScheme: "examplescheme://")
```
--------------------------------
### Define Tokenization Flow for Bank Card Repeat
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Specify the tokenization flow as `.bankCardRepeat` and provide the prepared `BankCardRepeatModuleInputData`.
```swift
let inputData: TokenizationFlow = .bankCardRepeat(bankCardRepeatModuleInputData)
```
--------------------------------
### Initialize CardIOView Delegate
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/CardIO/CardIO/README.md
In your view controller's viewDidLoad, check if the device can read cards with the camera. If capable, set the CardIOView's delegate to self. Otherwise, handle the unavailability appropriately.
```Objective-C
// SomeViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
if (![CardIOUtilities canReadCardWithCamera]) {
// Hide your "Scan Card" button, remove the CardIOView from your view, and/or take other appropriate action...
} else {
self.cardIOView.delegate = self;
}
}
```
--------------------------------
### Configure SberPay Application Scheme
Source: https://github.com/yoomoney/yookassa-payments-swift/blob/master/README.md
Specify the application scheme for returning to your app after a successful SberPay payment. This scheme is used in `TokenizationModuleInputData`.
```swift
let moduleData = TokenizationModuleInputData(
...
applicationScheme: "examplescheme://"
)
```
--------------------------------
### Apply Custom Branding with CustomizationSettings
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Customize the UI by applying a brand color to primary interactive elements using `CustomizationSettings`. This affects buttons, switches, and text-field highlights. A default blue color is used if none is specified.
```swift
// Use a custom brand color
let branding = CustomizationSettings(mainScheme: UIColor(named: "BrandBlue")!)
// Default (blueRibbon color)
let defaultBranding = CustomizationSettings()
let inputData = TokenizationModuleInputData(
clientApplicationKey: "live_XXXX",
shopName: "Store",
purchaseDescription: "Order",
amount: Amount(value: 100, currency: .rub),
customizationSettings: branding,
savePaymentMethod: .off
)
```
--------------------------------
### TokenizationSettings
Source: https://context7.com/yoomoney/yookassa-payments-swift/llms.txt
Controls which payment methods are shown in the checkout form and whether the YooKassa logo is displayed.
```APIDOC
## `TokenizationSettings`
Controls which payment methods are shown in the checkout form and whether the YooKassa logo is displayed.
```swift
// Show only bank cards and Apple Pay; hide the YooKassa logo
let settings = TokenizationSettings(
paymentMethodTypes: [.bankCard, .applePay],
showYooKassaLogo: false
)
// Show all available methods (default)
let allSettings = TokenizationSettings() // paymentMethodTypes: .all, showYooKassaLogo: true
// Use in TokenizationModuleInputData:
let inputData = TokenizationModuleInputData(
clientApplicationKey: "live_XXXX",
shopName: "Store",
purchaseDescription: "Order",
amount: Amount(value: 100, currency: .rub),
tokenizationSettings: settings,
savePaymentMethod: .off
)
```
```