- Tech Services
Concept Development
- Industry
- Emerging Tech
- Generative AI Hub
- Blog
- Contact Us
25
Feb. 215.6 K
VIEWSAuthorize.Net is a payment gateway service provider, It allows merchants to accept credit card and electronic check payments through their website and over an Internet Protocol connection. It is a safer way to process transactions online.
static let kClientKey = "5qwhb******************************************************43NsN" static let kClientName = "9r********5A" static let kClientTransationKey = "2w************7t" static let kValidationMode = "testMode" // liveMode static let kPaymentMode = AcceptSDKEnvironment.ENV_TEST //AcceptSDKEnvironment.ENV_LIVE static let kAuthorisedAPI = "https://apitest.authorize.net/" //https://api.authorize.net/ static let ApplePayMerchantID = "merchant.com.MyTestApp"
@IBOutlet weak var btnApplePay: UIButton!
import PassKit
var SupportedPaymentNetworks = [PKPaymentNetwork.amex, PKPaymentNetwork.cartesBancaires, PKPaymentNetwork.cartesBancaires, PKPaymentNetwork.chinaUnionPay, PKPaymentNetwork.discover, PKPaymentNetwork.eftpos, PKPaymentNetwork.electron, PKPaymentNetwork.elo, PKPaymentNetwork.idCredit, PKPaymentNetwork.interac, PKPaymentNetwork.JCB, PKPaymentNetwork.mada, PKPaymentNetwork.maestro, PKPaymentNetwork.masterCard, PKPaymentNetwork.privateLabel, PKPaymentNetwork.quicPay, PKPaymentNetwork.suica, PKPaymentNetwork.visa, PKPaymentNetwork.vPay]
@IBAction func btnApplePayTapped(_ sender: UIButton) {
//MARK: Checks apple pay is supported on current device or not
if PKPaymentAuthorizationViewController.canMakePayments() == false {
let alert = UIAlertController(title: "Apple Pay is not available", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
return self.present(alert, animated: true, completion: nil)
}
//MARK: checks apple pay is available then opens wallet app
if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: supportedNetworks) == false {
openWalletApp()
}
let tempDict = cartDetailsFetch?.value(forKey: "data") as! Dictionary <String, Any>
var totalPay : NSDecimalNumber?
let request = PKPaymentRequest()
request.currencyCode = "USD"
request.countryCode = "US"
// Set your apple pay merchant id
request.merchantIdentifier = Constants.ApplePayMerchantID
request.supportedNetworks = SupportedPaymentNetworks
// DO NOT INCLUDE PKMerchantCapability.capabilityEMV
request.merchantCapabilities = PKMerchantCapability.capability3DS
//MARK: pass total value and currency code to apple payment request
request.paymentSummaryItems = [
PKPaymentSummaryItem(label: "Total", amount: totalPay as! NSDecimalNumber)
]
let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request)
applePayController?.delegate = self
self.present(applePayController!, animated: true, completion: nil)
}
//MARK: opens wallet app
func openWalletApp() {
let library = PKPassLibrary()
library.openPaymentSetup()
}
//MARK: encrypt data and returns encrypted string
@objc func base64forData(_ theData: Data) -> String {
let charSet = CharacterSet.urlQueryAllowed
let paymentString = NSString(data: theData, encoding: String.Encoding.utf8.rawValue)!.addingPercentEncoding(withAllowedCharacters: charSet)
return paymentString!
}
func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: (@escaping (PKPaymentAuthorizationStatus) -> Void)) {
print("paymentAuthorizationViewController delegates called")
// completion(PKPaymentAuthorizationStatus.success)
print("Payment method data : \(payment.token.paymentMethod.description)")
print("Payment method data : \(payment.token.paymentData.description)")
if payment.token.paymentData.count > 0 {
let base64str = self.base64forData(payment.token.paymentData)
let message = String(format: "Data Value: %@", base64str)
let alert = UIAlertController(title: "Authorization Success", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
completion(PKPaymentAuthorizationStatus.success)
//call api
CallCreateCustApplePayProfile(payment: payment)
} else {
let alert = UIAlertController(title: "Authorization Failed!", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
completion(PKPaymentAuthorizationStatus.failure)
return self.performApplePayCompletion(controller, alert: alert)
}
}
//MARK: apple payment is finished then this method calls
@objc func performApplePayCompletion(_ controller: PKPaymentAuthorizationViewController, alert: UIAlertController) {
controller.dismiss(animated: true, completion: {() -> Void in
self.present(alert, animated: false, completion: nil)
})
}
func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
controller.dismiss(animated: true, completion: nil)
print("paymentAuthorizationViewControllerDidFinish called")
}
func CallCreateCustApplePayProfile(payment: PKPayment){
let tempDict = cartDetailsFetch?.value(forKey: "data") as! Dictionary <String, Any>
let addressData = UserDefaults.standard.value(forKey: "CheckOutAddress") as? Dictionary <String,Any>
let firstName = addressData!["first_name"] ?? ""
let lastName = addressData!["last_name"] ?? ""
let address1: String = addressData!["addres1"] as! String
let address2: String = addressData!["addres2"] as! String
let addressString = NSString(format: "%@,%@", address1,address2)
let city = addressData!["city_name"] ?? ""
let state = addressData!["state"] ?? ""
let zip = addressData!["pincode"] ?? ""
let country = ""
_ = addressData!["mobile"] ?? ""
let base64str = payment.token.paymentData.base64EncodedString()
print("Data value: \(base64str)")
let totalPay = tempDict["total"] as? String ?? "0.0"
//MARK: Send basic details to authorize.net api
let savecardJson = "{\r\n \"createTransactionRequest\": {\r\n \"merchantAuthentication\": {\r\n \"name\": \"\(Constants.kClientName)\",\r\n \"transactionKey\": \"\(Constants.kClientTransationKey)\" },\r\n \"transactionRequest\": {\r\n \"transactionType\": \"authCaptureTransaction\",\r\n \"amount\": \"\(totalPay)\",\r\n \"payment\": {\r\n \"opaqueData\":{\r\n \"dataDescriptor\": \"COMMON.APPLE.INAPP.PAYMENT\",\r\n \"dataValue\": \"\(base64str)\" } }, \r\n \"order\" : {\r\n \"invoiceNumber\" : \"\(self.invoiceNo)\", \r\n \"description\" : \"OrderFromiOS\"}, \r\n \"billTo\": {\r\n \"firstName\": \"\(firstName)\",\r\n \"lastName\": \"\(lastName)\",\r\n \"company\": \"\("company")\",\r\n \"address\": \"\(addressString)\",\r\n \"city\": \"\(city)\",\r\n \"state\": \"\(state)\",\r\n \"zip\": \"\(zip)\",\r\n \"country\": \"\(country)\"},\r\n \"shipTo\": {\r\n \"firstName\": \"\(firstName)\",\r\n \"lastName\": \"\(lastName)\",\r\n \"company\": \"\("company")\",\r\n \"address\": \"\(addressString)\",\r\n \"city\": \"\(city)\",\r\n \"state\": \"\(state)\",\r\n \"zip\": \"\(zip)\",\r\n \"country\": \"\(country)\"},\r\n \"customerIP\": \"\(IPAdress)\"}} }"
print("CallCreateCustApplePayProfile payment data : \(savecardJson)")
let jsonData = Data(savecardJson.utf8)
let request = NSMutableURLRequest(url: NSURL(string: "\(Constants.kAuthorisedAPI)xml/v1/request.api")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
//request.allHTTPHeaderFields = headers
request.httpBody = jsonData as Data
request.timeoutInterval = 60
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error ?? "")
let httpResponse = response as? HTTPURLResponse
print(httpResponse ?? "")
self.aryCreatePayProf = try! JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary as! [String : Any]
print("payment details from apple pay from error block :== \(self.aryCreatePayProf)")
_ = "\(Constants.APP_URL+URLs.placeOrder.rawValue)"
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse!)
self.aryCreatePayProf = try! JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary as! [String : Any]
print("payment details from apple pay :== \(self.aryCreatePayProf)")
let messages = self.aryCreatePayProf["messages"] as! Dictionary<String,Any>
let arymessages = messages["message"]! as! NSArray
let message = arymessages[0] as! Dictionary<String,Any>
if "\(message["code"]!)" == "I00001"
{
//call your server api here for submit data to your server
}
else {
DispatchQueue.main.async {
self.view.makeToast("\(message["text"]!)", duration: 5.0, position: .bottom)
ACProgressHUD.shared.hideHUD()
}
}
}
})
dataTask.resume()
}
You can see which params needed when authorize.net API calling from this link: https://developer.authorize.net/api/reference/index.html#mobile-in-app-transactions-create-an-apple-pay-transaction
To know more about us and the other services or solutions we provide, contact us.