ToolStripePayment.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. //
  2. // ToolStripePayment.swift
  3. // westkissMob
  4. //
  5. // Created by 王猛 on 2023/9/4.
  6. //
  7. import Foundation
  8. import UIKit
  9. import StripePaymentSheet
  10. import Stripe
  11. public typealias tt_currenttapclosure = (NSInteger , Any)->()
  12. public class ToolStripePayment: NSObject {
  13. @objc public var payFinishBlock:((String, String)->())?
  14. @objc public var order_id:String = ""
  15. @objc public var paymentMethodID:String = ""
  16. @objc public var req_baseUrl:String = ""
  17. @objc public var currentVC:UIViewController = UIViewController()
  18. @Published var paymentSheet: PaymentSheet?
  19. // @Published var paymentResult: PaymentSheetResult?
  20. @objc public func stripedidTapCheckoutButton(currentvc
  21. vc:UIViewController?,
  22. publishableKey:String,
  23. reqbaseUrl:String,
  24. amount:Int,
  25. currency:String,
  26. addressModel:ASAddressModel?,
  27. completion:tt_currenttapclosure?){
  28. currentVC = vc!
  29. req_baseUrl = reqbaseUrl
  30. STPAPIClient.shared.publishableKey = publishableKey;
  31. let intentConfig = PaymentSheet.IntentConfiguration(
  32. mode: .payment(amount: amount, currency: currency)
  33. ) { [self] paymentMethod, shouldSavePaymentMethod, intentCreationCallback in
  34. self.stripehandleConfirm(paymentMethod, shouldSavePaymentMethod, intentCreationCallback)
  35. }
  36. var configuration = PaymentSheet.Configuration()
  37. configuration.defaultBillingDetails.email = addressModel?.email
  38. // let string1:str = addressModel?.firstname
  39. // let string2 = "World!"
  40. // let combinedString = string1 + string2
  41. configuration.defaultBillingDetails.name = String(addressModel!.firstname + addressModel!.firstname)
  42. configuration.defaultBillingDetails.phone = addressModel?.telephone
  43. configuration.defaultBillingDetails.address.city = addressModel?.city
  44. configuration.defaultBillingDetails.address.country = addressModel?.country
  45. configuration.defaultBillingDetails.address.postalCode = addressModel?.postcode
  46. configuration.defaultBillingDetails.address.state = addressModel?.region.region
  47. configuration.defaultBillingDetails.address.line1 = addressModel?.street.first
  48. // print("=====street" + (addressModel?.street.first)! as Any)
  49. // configuration.allowsPaymentMethodsRequiringShippingAddress = true
  50. // STPUserInformation
  51. // let userInformation = STPUserInformation()
  52. // userInformation.email = "用户邮箱"
  53. // userInformation.phone = "用户电话"
  54. // let customer = PaymentSheet.CustomerConfiguration(id: "845600348@qq.com", ephemeralKeySecret: configuration.customer!.ephemeralKeySecret)
  55. //////
  56. // configuration.customer = customer
  57. configuration.applePay = .init(merchantId: "merchant.com.asteriahair.app", merchantCountryCode: "US")
  58. configuration.returnURL = "asteriaStripe://stripe-redirect" // Use the return url you set up in the previous step
  59. configuration.allowsDelayedPaymentMethods = true
  60. self.paymentSheet = PaymentSheet(intentConfiguration: intentConfig, configuration: configuration)
  61. self.paymentSheet?.present(from: vc!) { paymentResult in
  62. switch paymentResult {
  63. case .completed:
  64. print("sucess")
  65. // if completion != nil {
  66. // completion!(0,self.order_id)
  67. // }
  68. if self.payFinishBlock != nil {
  69. self.payFinishBlock!("1", self.paymentMethodID)
  70. }
  71. case .canceled:
  72. print("Canceled!")
  73. // completion!(1,"")
  74. if self.payFinishBlock != nil {
  75. self.payFinishBlock!("2", "Canceled")
  76. }
  77. case .failed(let error):
  78. print(error)
  79. // completion!(2,error)
  80. if self.payFinishBlock != nil {
  81. self.payFinishBlock!("3", "failed")
  82. }
  83. }
  84. }
  85. }
  86. func stripehandleConfirm(_ paymentMethod: STPPaymentMethod, _ shouldSavePaymentMethod: Bool, _ intentCreationCallback: @escaping (Result<String, Error>) -> Void) {
  87. stripeserverSideConfirmHandler(paymentMethod.stripeId, shouldSavePaymentMethod, intentCreationCallback);
  88. }
  89. func stripeserverSideConfirmHandler(_ paymentMethodID: String,
  90. _ shouldSavePaymentMethod: Bool,
  91. _ intentCreationCallback: @escaping (Result<String, Error>) -> Void) {
  92. // Create and confirm an intent on your server and invoke `intentCreationCallback` with the client secret
  93. stripeconfirmIntent(paymentMethodID: paymentMethodID, shouldSavePaymentMethod: shouldSavePaymentMethod) { result in
  94. switch result {
  95. case .success(let clientSecret):
  96. intentCreationCallback(.success(clientSecret))
  97. case .failure(let error):
  98. intentCreationCallback(.failure(error))
  99. }
  100. }
  101. }
  102. func stripeconfirmIntent(paymentMethodID: String,
  103. shouldSavePaymentMethod: Bool,
  104. completion: @escaping (Result<String, Error>) -> Void) {
  105. self.paymentMethodID = paymentMethodID;
  106. let payMethod: [String: Any?] = [
  107. "payment_method" : paymentMethodID,
  108. "manual_authentication" : "card",
  109. "payment_element" : true
  110. ]
  111. let body: [String: Any?] = [
  112. "method" : "stripe_payments",
  113. "additional_data" : payMethod,
  114. ]
  115. let param: [String: Any?] = [
  116. "paymentMethod" : body
  117. ]
  118. let order_requestUrl = req_baseUrl
  119. ASNetTools.shared().put(withPath: order_requestUrl, param:param as [AnyHashable : Any]) { json in
  120. if (json is NSNumber) {
  121. let orderId = json as! Int
  122. self.order_id = String(orderId)
  123. if self.payFinishBlock != nil {
  124. self.payFinishBlock!("0", self.order_id)
  125. }
  126. self.currentVC.dismiss(animated: true)
  127. } else {
  128. let clientSecret = json
  129. completion(.success(clientSecret as! String))
  130. }
  131. } faild: { code, msg in
  132. if msg.contains("Authentication Required:") {
  133. var client_secret = msg.replacingOccurrences(of: "Authentication Required:", with: "")
  134. client_secret = client_secret.replacingOccurrences(of: " ", with: "")
  135. print("client_secret" + client_secret)
  136. completion(.success(client_secret))
  137. } else {
  138. completion(.failure(ExampleError(errorDescription: (msg)) ))
  139. }
  140. }
  141. }
  142. struct ExampleError: LocalizedError {
  143. var errorDescription: String?
  144. }
  145. }