ApplePaybutton is not functioning (ApplePay integration with Stripe) - swift

I am trying to integrate Applepay using Stripe so that users are able to make easy payment. I use heroku account as a backend server. I could add the ApplePay Button on the UI (Please take a look at My Current Storyboard) and tried to configure a pop up check-out window coming from bottom for users to make payment.
My Current UI
However, even if I click the ApplePaybutton, nothing happens. My goal now is making the checkout window when users click the ApplePay Button My Goal UI.
I assume that func beginPayment() is supposed to be called when the button is pressed but doesn't work. I suspect that if (stripePublishableKey == "") { and codes after that is set incorrectly. Any help would be appreciated!
import UIKit
import Stripe
enum STPBackendChargeResult {
case success, failure
}
typealias STPTokenSubmissionHandler = (STPBackendChargeResult?, NSError?) -> Void
class ViewController: UIViewController, PKPaymentAuthorizationViewControllerDelegate {
let stripePublishableKey = "my Stripe PublishableKey"
let backendChargeURLString = "my heroku URL"
let appleMerchantId = "my apple merchand Id"
let shirtPrice : UInt = 1000 // this is in cents
override func viewDidLoad() {
super.viewDidLoad()
//This is the method of making the ApplePayButton( didn't use storyboard)
let button = PKPaymentButton(type: .buy, style: .black)
button.addTarget(self, action: #selector(ViewController.beginPayment(_:)), for: .touchUpInside)
let bw = button.frame.size.width
let bh = button.frame.size.height
let vw = view.frame.size.width
let vh = view.frame.size.height
button.frame = CGRect(origin: CGPoint(x: vw/2 - bw/2, y: vh/2 - bh/2), size: button.frame.size)
view.addSubview(button)
}
//This func is supposed to be called when ApplePayButton is pressed.
func beginPayment(_: UIButton) {
if (stripePublishableKey == "") {
let alert = UIAlertController(
title: "You need to set your Stripe publishable key.",
message: "You can find your publishable key at https://dashboard.stripe.com/account/apikeys .",
preferredStyle: UIAlertControllerStyle.alert
)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
return
}
if (appleMerchantId != "") {
let paymentRequest = Stripe.paymentRequest(withMerchantIdentifier: appleMerchantId)
if Stripe.canSubmitPaymentRequest(paymentRequest) {
paymentRequest.paymentSummaryItems = [PKPaymentSummaryItem(label: "Cool shirt", amount: NSDecimalNumber(string: "10.00")), PKPaymentSummaryItem(label: "Stripe shirt shop", amount: NSDecimalNumber(string: "10.00"))]
let paymentAuthVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)
paymentAuthVC.delegate = self
self.present(paymentAuthVC, animated: true, completion: nil)
return
}
} else {
print("You should set an appleMerchantId.")
}
}
func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: #escaping ((PKPaymentAuthorizationStatus) -> Void)) {
let apiClient = STPAPIClient(publishableKey: stripePublishableKey)
apiClient.createToken(with: payment, completion: { (token, error) -> Void in
if error == nil {
if let token = token {
self.createBackendChargeWithToken(token, completion: { (result, error) -> Void in
if result == STPBackendChargeResult.success {
completion(PKPaymentAuthorizationStatus.success)
}
else {
completion(PKPaymentAuthorizationStatus.failure)
}
})
}
}
else {
completion(PKPaymentAuthorizationStatus.failure)
}
})
}
func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
dismiss(animated: true, completion: nil)
}
func createBackendChargeWithToken(_ token: STPToken, completion: #escaping STPTokenSubmissionHandler) {
if backendChargeURLString != "" {
if let url = URL(string: backendChargeURLString + "/charge") {
let session = URLSession(configuration: URLSessionConfiguration.default)
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
let postBody = "stripeToken=\(token.tokenId)&amount=\(shirtPrice)"
let postData = postBody.data(using: String.Encoding.utf8, allowLossyConversion: false)
session.uploadTask(with: request as URLRequest, from: postData, completionHandler: { data, response, error in
let successfulResponse = (response as? HTTPURLResponse)?.statusCode == 200
if successfulResponse && error == nil {
completion(.success, nil)
} else {
if error != nil {
completion(.failure, error as NSError?)
} else {
completion(.failure, NSError(domain: StripeDomain, code: 50, userInfo: [NSLocalizedDescriptionKey: "There was an error communicating with your payment backend."]))
}
}
}).resume()
return
}
}
completion(STPBackendChargeResult.failure, NSError(domain: StripeDomain, code: 50, userInfo: [NSLocalizedDescriptionKey: "You created a token! Its value is \(token.tokenId). Now configure your backend to accept this token and complete a charge."]))
}
}

Related

CCavenue Payment Gateway with WKWebView - iOS (as UiWebview is deprecated since 2020 by apple)

Post December 2020, apple does not allow UiWebView support. ccavenue, being popular payment gateway in India, still have not updated their sdk from official website.
Here is the the complete code, to be replaced for UiWebView issue.
class CCWebViewController: BaseViewController, WKNavigationDelegate {
var mywebview: WKWebView!
var request: NSMutableURLRequest?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupWebView()
notification = NotificationCenter.default.addObserver(forName: .UIApplicationWillEnterForeground, object: nil, queue: .main) {
[unowned self] notification in
self.checkResponseUrl()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !isHere {
isHere = true
self.gettingRsaKey(){
(success, object) -> () in
DispatchQueue.main.sync {
if success {
self.encyptCardDetails(data: object as! Data)
}
else{
self.displayAlert(msg: object as! String)
}
}
}
}
}
override func viewDidAppear(_ animated: Bool) {
LoadingOverlay.shared.showOverlay(view: self.view)
}
private func setupWebView(){
//setup webview
let config = WKWebViewConfiguration()
self.mywebview = WKWebView(frame: CGRect.init(x: self.view.bounds.origin.x, y: self.view.bounds.origin.y, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), configuration: config)
mywebview.navigationDelegate = self
self.view.addSubview(mywebview)
}
private func gettingRsaKey(completion: #escaping (_ success: Bool, _ object: AnyObject?) -> ()){
DispatchQueue.main.async {
self.rsaKeyDataStr = "access_code=\(self.accessCode)&order_id=\(self.orderId)"
let requestData = self.rsaKeyDataStr.data(using: String.Encoding.utf8)
guard let urlFromString = URL(string: self.rsaKeyUrl) else{
return
}
var urlRequest = URLRequest(url: urlFromString)
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
urlRequest.httpMethod = "POST"
urlRequest.httpBody = requestData
let session = URLSession(configuration: URLSessionConfiguration.default)
print("session",session)
session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode{
guard let responseData = data else{
print("No value for data")
completion(false, "Not proper data for RSA Key" as AnyObject?)
return
}
print("data :: ",responseData)
completion(true, responseData as AnyObject?)
}
else{
completion(false, "Unable to generate RSA Key please check" as AnyObject?) }
}.resume()
}
}
private func encyptCardDetails(data: Data){
guard let rsaKeytemp = String(bytes: data, encoding: String.Encoding.ascii) else{
print("No value for rsaKeyTemp")
return
}
rsaKey = rsaKeytemp
rsaKey = self.rsaKey.trimmingCharacters(in: CharacterSet.newlines)
rsaKey = "-----BEGIN PUBLIC KEY-----\n\(self.rsaKey)\n-----END PUBLIC KEY-----\n"
print("rsaKey :: ",rsaKey)
let myRequestString = "amount=\(amount)&currency=\(currency)"
do{
let encodedData = try RSAUtils.encryptWithRSAPublicKey(str: myRequestString, pubkeyBase64: rsaKey)
var encodedStr = encodedData?.base64EncodedString(options: [])
let validCharSet = CharacterSet(charactersIn: "!*'();:#&=+$,/?%#[]").inverted
encodedStr = encodedStr?.addingPercentEncoding(withAllowedCharacters: validCharSet)
CCWebViewController.statusCode = 0
//Preparing for webview call
if CCWebViewController.statusCode == 0{
CCWebViewController.statusCode = 1
let urlAsString = "https://secure.ccavenue.com/transaction/initTrans"
let encryptedStr = "merchant_id=\(merchantId)&order_id=\(orderId)&redirect_url=\(redirectUrl)&cancel_url=\(cancelUrl)&enc_val=\(encodedStr!)&access_code=\(accessCode)&billing_name=\(billingName)&billing_address=\(billingAddress)&billing_city=\(billingCity)&billing_state=\(billingState)&billing_country=\(billingCountry)&billing_tel=\(billingMobile)&billing_zip=\(pincode)&billing_email=\(billingEmail)&merchant_param1=\(notes)&billing_country=\(billingCountry)&merchant_param2=\(notes)&merchant_param3=\(notes)&merchant_param4=\(notes)&delivery_country=\(billingCountry)&delivery_cust_notes=\(notes)"
let myRequestData = encryptedStr.data(using: String.Encoding.utf8)
request = NSMutableURLRequest(url: URL(string: urlAsString)! as URL, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 30)
request?.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
request?.setValue(urlAsString, forHTTPHeaderField: "Referer")
request?.httpMethod = "POST"
request?.httpBody = myRequestData
self.mywebview.load(request! as URLRequest)
}
else{
print("Unable to create requestURL")
displayAlert(msg: "Unable to create requestURL")
}
}
catch let err {
print(err)
}
}
func displayAlert(msg: String){
let alert: UIAlertController = UIAlertController(title: "ERROR", message: msg, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
LoadingOverlay.shared.hideOverlayView()
self.dismiss(animated: true, completion: nil)
}
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
//MARK: WebviewDelegate Methods
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
self.showToast(type: 0, message: "Error", timeToDisplay: 2)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print(String(describing: webView.url))
LoadingOverlay.shared.hideOverlayView()
webView.evaluateJavaScript("document.documentElement.outerHTML", completionHandler: { result, error in
if let datHtml = result as? String {
print(datHtml)
// parse datHtml here
let string = webView.url!.absoluteString
if(string.contains(self.redirectUrl))
{
print(self.mywebview.isLoading)
let html = datHtml
print("html :: ",html)
var transStatus = "Not Known"
if(html.contains("tracking_id"))
{
if(html.contains("Success"))
{
transStatus = "Transaction Successful"
let controller: CCResultViewController = CCResultViewController()
controller.transStatus = transStatus
controller.isSucceed = true
self.present(controller, animated: true, completion: nil)
}
else if(html.contains("Aborted"))
{
transStatus = "Transaction Cancelled"
let controller: CCResultViewController = CCResultViewController()
controller.transStatus = transStatus
controller.isSucceed = false
self.present(controller, animated: true, completion: nil)
}
else
{
transStatus = "Transaction Failed"
let controller: CCResultViewController = CCResultViewController()
controller.transStatus = transStatus
controller.isSucceed = false
self.present(controller, animated: true, completion: nil)
}
}
else{
print("html does not contain any related data")
self.displayAlert(msg: "html does not contain any related data for this transaction.")
}
}
}
} )
}
}

How to add function after the "return data"

I have a problem where my program could run but some of the code didn't work. There was no error but it has a warning sign says that the "code after return will not executed". I would like a help on that. Thank you
#IBAction func newBookTapped(_ sender: Any) {
guard let uid = Auth.auth().currentUser?.uid,
let data = bookData() else {
return
}
db.collection("new reading").document(uid).setData(data)
}
func bookData() -> [String: Any]? {
guard let title = bookTitleTextField.text,
let author = bookAuthorTextField.text,
let summary = bookSummaryTextField.text else {
return nil
}
let data: [String: Any] = [
"bookTitle": title,
"bookAuthor": author,
"bookSummary": summary
]
return data
self.transitionToMenu()
}
func transitionToMenu() {
let alert = UIAlertController(title: nil, message: "Book has been saved!", preferredStyle: .alert)
alert.view.alpha = 0.5
alert.view.layer.cornerRadius = 15
self.present(alert, animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
if let navController = self.navigationController {
navController.popViewController(animated: true)
} else {
self.dismiss(animated: true, completion: {})
}
}
}
My program photo
When making a return you end the function and go back to the call so there is no way that anything after a return in a function is being executed.
You have to put the self.transitionToMenu() before the return data.

Swift: Hold code execution until API response received

I need to set up authorization screen:
1) Login and pass is inputted
2) App requests token from API
3) Response is received
4) App checks if response contains token: if contains, should perform authorization
PROBLEM TO SOLVE: app makes 4) before step 3)
What I tried: I used escaping closure in order to hold the execution until API data is received, but it helped only partially - it helped to hold only assignment of value to token, but I cannot hold 'if checks' still.
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == "loginSegue" {
let login = loginInput.text!
let password = passInput.text!
tokenLoader.getToken(login: login, password: password) { [weak self] token in
self?.token = token.access_token
}
//THIS CODE I NEED TO HOLD UNTIL DATA FROM API RECEIVED
if token != "" {
return true
} else {
let alert = UIAlertController(title: nil, message: "Incorrect password", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
return false
}
//
} else {
return true
}
}
class TokenLoader {
let session = Session.instance
let baseUrl = "http://46.254.18.193:9096"
func getToken(login: String, password: String, completion: #escaping (AccessToken) -> Void) {
let path = "/token"
let parameters: Parameters = [
"grant_type": "client_credentials",
"client_id": login,
"client_secret": password,
"scope": "read"
]
let url = baseUrl+path
AF.request(url, method: .get, parameters: parameters).responseData { response in
do {
let token = try JSONDecoder().decode(AccessToken.self, from: response.value!)
print(token)
self.session.token = token.access_token
completion(token)
} catch {
print(error)
}
}
}
}
You can resolve the issue using this function ... perform it on event when you want to segue or to get token
func getTokenAndPerformSegue() {
let login = loginInput.text
let password = passInput.text
if let getLogin = login ,let getPassword = password {
tokenLoader.getToken(login: getLogin, password: getPassword) { [weak self] token in
self?.token = token.access_token
if token.isEmpty() {
let alert = UIAlertController(title: nil, message: "Incorrect password", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
} else {
performSegue(withIdentifier: "loginSegue", sender: nil)
}
}
}
}
you need to write it like this ... to return nil or error in completion
func getToken(login: String, password: String, completion: #escaping (AccessToken?) -> Void) {
let path = "/token"
let parameters: Parameters = [
"grant_type": "client_credentials",
"client_id": login,
"client_secret": password,
"scope": "read"
]
let url = baseUrl+path
AF.request(url, method: .get, parameters: parameters).responseData { response in
do {
let token = try JSONDecoder().decode(AccessToken.self, from: response.value!)
print(token)
self.session.token = token.access_token
completion(token)
} catch {
completion(nil)
print(error)
}
}
}
Let me know if you did not get anything or you need further help

completion handler can not dismiss the popAlertController

I have a view controller with a single textView which I get a string from server and set on it.
I call a http-get service in viewDidAppear and I need to show a popUp alert for waiting user till get the string
I do all but I can not dismiss the popalert and app stacks in loading alert
override func viewWillAppear(_ animated: Bool) {
fetchAndPrintEachPerson()
networkReachablity()
popUpLoading() // start showing loading pop alert
getPerson ()
}
override func viewDidLoad() {
super.viewDidLoad()
style()
giftTextFiled.isEnabled = false
}
func popUpLoading(){
popUpAlert = UIAlertController(title: nil, message: "wait ...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.startAnimating();
popUpAlert.view.addSubview(loadingIndicator)
present(popUpAlert, animated: true, completion: nil)
}
func getPerson(){
guard let url=URL(string: "\(address)person/code") else {return}
print(url)
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let res=response {
//print(res)
}
do {
if let dataContent=data {
let con = try? JSONSerialization.jsonObject(with: dataContent, options: []) as? AnyObject
let data = con??["data"] as? AnyObject
let code = data?["code"] as? String
print(code)
// self.popUpAlert.dismiss(animated: true, completion: {
DispatchQueue.main.async(execute: {
//self.giftTextFiled.text=code!
self.giftTextFiled.isEnabled = true
self.popUpAlert.dismiss(animated: true, completion: nil)
})
//})
}else {
let snack=snackBarAlert()
snack.alert(title: "error", color: UIColor.red)
self.popUpAlert.dismiss(animated: true, completion: nil)
}
}catch let err{
print(err)
DispatchQueue.main.async(execute: {
self.popUpAlert.dismiss(animated: true, completion: nil)
})
}
}.resume()
}
update first post.
Try putting that inside view DidLoad & check whether your getting a response from the server other wise it will fall through else block and keep showing the pop up
URLSession.shared.dataTask completion closure is called on non-main thread, which may produce unexpected results for UI. Dispatch your UI code to main thread.
URLSession.shared.dataTask(with: url) { (data, response, error) in
DispatchQueue.main.async {
// Your UI related code
}
}.resume()

use of unresolved identifier 'result' swift 3

I'm writing a login page for my app and i'm getting this error
social media app , xcode 8.3.2 , swift 3
i've tried target membership in file inspector and nothing changed
also I removed test units (UITest and Test) and renew them , it didn't worked either.
at the line 41 I'm getting this error "use of unresolved identifier 'result'"
the picture below explains the code
Picture
import UIKit
class LoginViewController : UIViewController
{
#IBOutlet weak var txt_username: UITextField!
#IBOutlet weak var txt_password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func btn_log_in_click(_ sender: Any){
let server=MultipartUtility (Url:"http://x.x.x.x/appname-api/user/login/")
//I.m hiding the real ip and details for posting this
server.AddFormField("username", value: txt_username.text)
server.AddFormField("password", value: txt_password.text)
let task = URLSession.shared.dataTask(with: server.execute())
{Data,URLResponse,error in
if error != nil{
print(error as Any)
return
}
do{
let json = try JSONSerialization.jsonObject(with: Data!, options: .allowFragments)
if let json_result = json as? [String: Any]{
let result = json_result ["result"] as? String
if result == "0"
{
DispatchQueue.main.async {
let alert = UIAlertController(title:"Incorrect Username",message : "The username you entered doesn't appear to belong to an account. Please check your username and try again", preferredStyle : .alert)
let alert_action = UIAlertAction(title: "Try Again", style: .default, handler: nil)
alert.addAction(alert_action)
self.present(alert, animated: true, completion: nil)
}
}
}
else{
DispatchQueue.main.async {
UserDefaults.standard.set(result!, forKey: "user_id")
//" use of unresolved identifier 'result' "
let current_view=UIApplication.shared.windows[0] as UIWindow
let new_view=(self.storyboard? .instantiateViewController(withIdentifier: "tab_bar"))! as UIViewController
UIView.transition(from: (current_view.rootViewController? .view)!, to:new_view.view , duration: 0.65, options: .transitionFlipFromRight, completion: {(action) in current_view.rootViewController=new_view
})
}
}
}
catch{
}
}
task.resume()
}
}
if let json_result = json as? [String: Any]
{
let result = json_result ["result"] as? String
if result == "0"
{
DispatchQueue.main.async {
let alert = UIAlertController(title:"Incorrect Username",message : "The username you entered doesn't appear to belong to an account. Please check your username and try again", preferredStyle : .alert)
let alert_action = UIAlertAction(title: "Try Again", style: .default, handler: nil)
alert.addAction(alert_action)
self.present(alert, animated: true, completion: nil)
}
}
else
{
DispatchQueue.main.async {
UserDefaults.standard.set(result!, forKey: "user_id")
//" use of unresolved identifier 'result' "
let current_view=UIApplication.shared.windows[0] as UIWindow
let new_view=(self.storyboard? .instantiateViewController(withIdentifier: "tab_bar"))! as UIViewController
UIView.transition(from: (current_view.rootViewController? .view)!, to:new_view.view , duration: 0.65, options: .transitionFlipFromRight, completion: {(action) in current_view.rootViewController=new_view
})
}
}
}
else{
// Error in jsonSerialization
}