SDK para iOS
Instalar
Opção 1: CocoaPods
Adicione ao seu Podfile:
pod 'YunoSDK'instalação do podOpção 2: Gerenciador de Pacotes Swift
No Xcode: Arquivo → Adicionar dependências do pacote
https://github.com/yuno-payments/yuno-sdk-ios
Requisitos: iOS 14.0+, Swift 5.7+
Initialize
AppDelegate.swift ou estrutura App:
import YunoSDK
// In AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions...) -> Bool {
Yuno.initialize(apiKey: "your-public-api-key")
return true
}
// Or in SwiftUI App struct
init() {
Yuno.initialize(apiKey: "your-public-api-key")
}Fluxo básico de pagamentos
Exemplo SwiftUI
import SwiftUI
import YunoSDK
struct PaymentView: View {
@State private var showPayment = false
@StateObject private var viewModel = PaymentViewModel()
var body: some View {
VStack {
Text("Total: $25.00")
.font(.title)
Button("Pay Now") {
Task {
await viewModel.startPayment()
}
}
}
.task {
await viewModel.initialize()
}
}
}
@MainActor
class PaymentViewModel: ObservableObject, YunoPaymentFullDelegate {
private var _checkoutSession: String = ""
private var _countryCode: String = "US"
private var paymentMethodsView: UIView?
// YunoPaymentFullDelegate required properties
var checkoutSession: String { _checkoutSession }
var countryCode: String { _countryCode }
var language: String? { "en" }
var viewController: UIViewController? { nil }
func initialize() async {
// Create checkout session on backend
let session = await createCheckoutSession()
_checkoutSession = session.checkoutSession
// Get payment methods view from SDK
paymentMethodsView = await Yuno.getPaymentMethodViewAsync(delegate: self)
// Add view to your UI hierarchy (in SwiftUI, use UIViewRepresentable)
}
func startPayment() async {
// Start payment - SDK reads session from delegate properties
Yuno.startPayment()
}
// YunoPaymentFullDelegate methods
func yunoCreatePayment(with token: String, information: [String: Any]) {
Task {
await createPayment(token: token)
Yuno.continuePayment(showPaymentStatus: true)
}
}
func yunoPaymentResult(_ result: Yuno.Result) {
switch result {
case .success:
print("Payment succeeded")
case .failure(let error):
print("Payment failed:", error)
}
}
func yunoUpdatePaymentMethodsViewHeight(_ height: CGFloat) {
// Called when payment methods view height changes
print("Payment methods view height:", height)
}
func yunoDidSelect(paymentMethod: PaymentMethodSelected) {
// Called when user selects a payment method
print("Selected payment method:", paymentMethod)
}
}
func createCheckoutSession() async -> CheckoutSession {
// Call your backend
let response = try? await URLSession.shared.data(from: URL(string: "https://api.example.com/checkout")!)
return try! JSONDecoder().decode(CheckoutSession.self, from: response!.0)
}Exemplo do UIKit
import UIKit
import YunoSDK
class PaymentViewController: UIViewController, YunoPaymentFullDelegate {
private var _checkoutSession: String = ""
private var paymentMethodsView: UIView?
// YunoPaymentFullDelegate required properties
var checkoutSession: String { _checkoutSession }
var countryCode: String { "US" }
var language: String? { "en" }
var viewController: UIViewController? { self }
override func viewDidLoad() {
super.viewDidLoad()
Task {
// 1. Create session on backend
let session = await createCheckoutSession()
_checkoutSession = session.checkoutSession
// 2. Get payment methods view from SDK
paymentMethodsView = await Yuno.getPaymentMethodViewAsync(delegate: self)
// 3. Add payment methods view to hierarchy
if let methodsView = paymentMethodsView {
methodsView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(methodsView)
NSLayoutConstraint.activate([
methodsView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
methodsView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
methodsView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
}
// 4. Add pay button
let payButton = UIButton(type: .system)
payButton.setTitle("Pay Now", for: .normal)
payButton.addTarget(self, action: #selector(payButtonTapped), for: .touchUpInside)
payButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(payButton)
NSLayoutConstraint.activate([
payButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
payButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
}
}
@objc func payButtonTapped() {
// Start payment - SDK reads session from delegate properties
Yuno.startPayment()
}
// YunoPaymentFullDelegate methods
func yunoCreatePayment(with token: String, information: [String: Any]) {
Task {
await createPayment(token: token, checkoutSession: _checkoutSession)
Yuno.continuePayment(showPaymentStatus: true)
}
}
func yunoPaymentResult(_ result: Yuno.Result) {
switch result {
case .success:
navigationController?.pushViewController(SuccessViewController(), animated: true)
case .failure(let error):
showAlert(message: "Payment failed: \(error.localizedDescription)")
}
}
func yunoUpdatePaymentMethodsViewHeight(_ height: CGFloat) {
// Called when payment methods view height changes
// Update constraints if needed
print("Payment methods view height:", height)
}
func yunoDidSelect(paymentMethod: PaymentMethodSelected) {
// Called when user selects a payment method
print("Selected payment method:", paymentMethod)
}
}Tratamento dos resultados de pagamento
func yunoPaymentResult(_ result: Yuno.Result) {
switch result {
case .success(let data):
switch data.status {
case "SUCCEEDED":
navigateToSuccess()
case "PENDING":
showPendingMessage()
default:
break
}
case .failure(let error):
switch error.code {
case .cardDeclined:
showError("Card was declined")
case .insufficientFunds:
showError("Insufficient funds")
case .networkError:
showError("Network error, please try again")
default:
showError("Payment failed: \(error.localizedDescription)")
}
}
}Autenticação 3DS
O 3DS é tratado automaticamente. Para métodos de pagamento assíncronos:
func yunoCreatePayment(with token: String, information: [String: Any]) {
Task {
await createPayment(token: token)
// Handle redirects if needed
let result = await Yuno.continuePayment(showPaymentStatus: false)
if let redirectURL = result?.redirectURL {
// Open redirect URL
UIApplication.shared.open(redirectURL)
}
}
}Opções de configuração
Parâmetros essenciais
| Parâmetro | Tipo | Descrição |
|---|---|---|
checkoutSession | Cordas | ID da sessão do backend |
countryCode | Cordas | Código ISO do país (por exemplo, “US”) |
language | String? | Código do idioma (por exemplo, “en”) |
viewController | UIViewController? | Para apresentar a interface do usuário de pagamento (UIKit) |
Configuração do cartão
let config = YunoConfig(
checkoutSession: session.id,
countryCode: "US",
cardSaveEnable: true, // Mostrar caixa de seleção para salvar
cardFormType: .default, // ou .extended
allowedPaymentTypes: [.credit, .debit]
)Aparência
Yuno.Appearance.corPrimária = .systemBlue
Yuno.Appearance.corDeFundo = .systemBackground
Yuno.Appearance.fonte = .systemFont(ofSize: 16)
Yuno.Appearance.raioDeCanto = 8.0Próximos passos
Pronto para explorar recursos mais avançados? Confira o guia Recursos avançados para:
- Opções alternativas de montagem -
startPaymentLite()estartPaymentSeamlessLite()para seleção de método de pagamento personalizado - Inscrição (Salvar cartões) - Salve métodos de pagamento para uso futuro
- Token armazenados - Pagamentos com um clique com cartões salvos
- IU personalizada (integração sem interface) - Crie formulários de pagamento totalmente personalizados
- Integração do modo de renderização - Exiba o formulário de pagamento em sua visualização personalizada
- Estilo e aparência - Personalizar a aparência do SDK
- Concorrência no Swift 6 - Lide com avisos de concorrência usando anotações adequadas
- Integração ClearSale - Prevenção de fraudes
Veja também:
- Exemplos de código - Exemplos para copiar e colar em cenários comuns
- Notas de lançamento - Versões do SDK, alterações e guias de migração
Atualizado há 1 dia