target 'Project name' do
pod 'PayBoxSdk', :git => 'https://github.com/PayBox/SDK_iOS-input-.git', :submodules => true
end
$ pod install
let sdk = PayboxSdk.initialize(merchantId: merchantID, secretKey: "secretKey")
let paymentView = PaymentView(frame: CGRect(x: 0, y: 0, width: width, height: height))
sdk.setPaymentView(paymentView: paymentView)
paymentView.delegate = self
func loadStarted() {
}
func loadFinished() {
}
sdk.config().testMode(enabled: true) // По умолчанию тестовый режим включен
sdk.config().setRegion(region: .DEFAULT) //Region.DEAFAULT по умолчанию
sdk.config().setPaymentSystem(paymentSystem: paymentSystem)
sdk.config().setCurrencyCode(code: "KZT")
sdk.config().autoClearing(enabled: enabled)
sdk.config().setEncoding(encoding: "UTF-8") // по умолчанию UTF-8
sdk.config().setRecurringLifetime(lifetime: 36) //по умолчанию 0 месяцев (параметр исключается из списка при значении 0)
sdk.config().setPaymentLifetime(lifetime: 300) //по умолчанию 300 секунд
recurringMode(enabled: enabled) //по умолчанию отключен
sdk.config().setUserPhone(userPhone: userPhone)
sdk.config().setUserEmail(userEmail: email)
sdk.config().setLanguage(language: .ru)
sdk.config().setCheckUrl(url: url)
sdk.config().setResultUrl(url: url)
sdk.config().setRefundUrl(url: url)
sdk.config().setClearingUrl(url: url)
sdk.config().setRequestMethod(requestMethod: requestMethod)
sdk.config().setFrameRequired(isRequired: true) //false по умолчанию
sdk.createPayment(amount: amount, description: "description", orderId: "orderId", userId: userId, extraParams: extra) {
payment, error in //Вызовется после оплаты
}
sdk.createRecurringPayment(amount: amount, description: "description", recurringProfile: "profile", orderId: "orderId", extraParams: extra) {
recurringPayment, error in // Вызовется после оплаты
}
sdk.getPaymentStatus(paymentId: paymentId) {
status, error in // Вызовется после получения ответа
}
sdk.makeClearingPayment(paymentId: paymentId, amount: amount) { // Если указать nil вместо суммы клиринга, то клиринг пройдет на всю сумму платежа
capture, error in // Вызовется после клиринга
}
sdk.makeCancelPayment(paymentId: paymentId) {
payment, error in // Вызовется после отмены
}
sdk.makeRevokePayment(paymentId: paymentId, amount: amount) {
payment, error in // Вызовется после возврата
}
sdk.addNewCard(postLink: url, userId: userId) {
payment, error in // Вызовется после сохранения
}
sdk.getAddedCards(userId: userId) {
cards, error in // Вызовется после получения ответа
}
sdk.removeAddedCard(cardId: cardId, userId: userId) {
payment, error in // Вызовется после ответа
}
sdk.createCardPayment(amount: amount, userId: userId, cardToken: "cardToken", description: "description", orderId: "01234", extraParams: nil) {
payment, error in // Вызовется после создания
}
sdk.payByCard(paymentId: paymentId) {
payment, error in // Вызовется после оплаты
}
sdk.createNonAcceptancePayment(paymentId: paymentId){
payment, error -> //Вызовется после оплаты
}
import PassKit
func applePayStatus() -> (canMakePayments: Bool, canSetupCards: Bool) {
return (PKPaymentAuthorizationController.canMakePayments(),
PKPaymentAuthorizationController.canMakePayments(usingNetworks: supportedNetworks))
}
let supportedNetworks: [PKPaymentNetwork] = [
.masterCard,
.visa
]
@objc func initApplePay(_: AnyObject) {
// Товары в корзине
let item1 = PKPaymentSummaryItem(label: "Item 1", amount: NSDecimalNumber(string: "4.00"), type: .final)
let item2 = PKPaymentSummaryItem(label: "Item 2", amount: NSDecimalNumber(string: "1.00"), type: .final)
// Наименование магазина и итоговая цена
let total = PKPaymentSummaryItem(label: "Your company name", amount: NSDecimalNumber(string: "5.00"), type: .final)
let paymentSummaryItems = [item1, item2, total]
// Подготовка запроса оплаты Apple Pay
let paymentRequest = PKPaymentRequest()
paymentRequest.paymentSummaryItems = paymentSummaryItems
paymentRequest.merchantIdentifier = "your_merchant_identifier" // заменить на актуальный MerchantID из консоли разработчика Apple
paymentRequest.merchantCapabilities = .threeDSecure
paymentRequest.countryCode = "KZ"
paymentRequest.currencyCode = "KZT"
paymentRequest.supportedNetworks = supportedNetworks
// Отображение контроллера Apple Pay
let paymentController = PKPaymentAuthorizationController(paymentRequest: paymentRequest)
paymentController.delegate = self
paymentController.present(completion: { (presented: Bool) in
if presented {
debugPrint("Presented payment controller")
} else {
debugPrint("Failed to present payment controller")
}
})
}
func finishApplePayPayment(tokenData: Data, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {
let amount: Float = 5
let description = "some description"
let orderId = "1234"
let userId = "1234"
sdk.createApplePayment(amount: amount, description: description, orderId: orderId, userId: userId, extraParams: nil) {
paymentId, error in {
self.sdk.confirmApplePayment(paymentId: paymentId ?? "", tokenData: tokenData) {
confirmPayment, confirmError in {
if let directError = confirmError {
completion(PKPaymentAuthorizationResult(status: .failure, errors: nil))
// Ошибка платежа
} else if let directPay = confirmPayment {
completion(PKPaymentAuthorizationResult(status: .success, errors: nil))
// Успешный платеж
}
}()
}
}()
}
}
lazy var applePayButton: UIButton! = {
let button = PKPaymentButton(paymentButtonType: .plain, paymentButtonStyle: .black)
button.translatesAutoresizingMaskIntoConstraints = false
button.frame = CGRect.zero
button.clipsToBounds = true
button.contentEdgeInsets = UIEdgeInsets(top: 0,left: 10,bottom: 0,right: 10)
button.backgroundColor = UIColor.black
button.layer.cornerRadius = 25
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor
return button
}()
self.view.addSubview(applePayButton)
NSLayoutConstraint.activate([
applePayButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
applePayButton.topAnchor.constraint(equalTo: guide.topAnchor, constant: 30),
applePayButton.widthAnchor.constraint(equalToConstant: 250),
applePayButton.heightAnchor.constraint(equalToConstant: 50)
])
applePayButton.addTarget(self, action: #selector(self.initApplePay(_:)), for: .touchUpInside)
let applePayStatus = applePayStatus()
applePayButton.isHidden = !applePayStatus.canMakePayments
class ViewController: UIViewController, WebDelegate, PKPaymentAuthorizationControllerDelegate
//Скрываем контроллер Apple Pay самостоятельно
func paymentAuthorizationControllerDidFinish(_ controller: PKPaymentAuthorizationController) {
controller.dismiss()
}
//Получаем токен от Apple Pay и передаем в функцию `finishApplePayPayment` для взаимодействия с SDK
func paymentAuthorizationController(_ controller: PKPaymentAuthorizationController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {
finishApplePayPayment(tokenData: payment.token.paymentData, handler: completion)
}