简体   繁体   English

如何在iOS项目中正确实现Stripe?

[英]How to properly implement Stripe in iOS project?

Im developing an iOS app and its includes selling goods outside of the app so I downloaded Stripe using Cocoapods and placing it in my poodle. 我正在开发一个iOS应用程序,其中包括在应用程序外销售商品,因此我使用Cocoapods下载了Stripe,并将其放在了贵宾犬中。 I know I have correctly installed in my app and input my test API key, because it import Stripe line works just fine. 我知道我已经正确安装了我的应用程序并输入了我的测试API密钥,因为它可以import Stripe行。 However I am having trouble creating a token. 但是我在创建令牌时遇到了麻烦。 Every time I try to run my code in the simulator and try to make a purchase it prints there was an error. 每次我尝试在模拟器中运行我的代码并尝试进行购买并打印时,都会出现错误。 I don't know if its because I implemented the wrong line of code somewhere or left some out, so I was wondering if anybody could help me figure out why the purchase isn't going through? 我不知道是否是因为我在某处实施了错误的代码行或遗漏了一些代码,所以我想知道是否有人可以帮助我弄清楚为什么购买没有通过? I know I don't have a backend set up but I'm not trying to send the token to the server yet I'm just trying to make sure my app is connected to Stripe which is the first step of 6 that require to actually make a purchase. 我知道我没有设置后端,但是我没有尝试将令牌发送到服务器,但是我只是想确保我的应用程序已连接到Stripe,这是6的第一步,实际上需要进行购买。 Thanks for your help in advance. 感谢您的帮助。

Code for view controller before the one that lets user (through firebase authentication) make a purchase and stores data: 允许用户(通过Firebase身份验证)购买并存储数据的视图控制器之前的代码:

import UIKit

class PaymentInfoController: UIViewController {


@IBOutlet weak var paymentLabel: UILabel!
@IBOutlet weak var cardField: UITextField!
@IBOutlet weak var cvcField: UITextField!
@IBOutlet weak var expField: UITextField! 

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {   

    if let checkoutVC = segue.destination as? CheckoutController {
        checkoutVC.cardNumber = self.cardField.text!
        checkoutVC.cvc = self.cvcField.text!

        if self.expField.text?.isEmpty == false {

            expField.text?.contains("0123456789/")
            (expField.text?.characters.count)! <= 7
        let expDate = self.expField.text?.components(separatedBy: "/")
        let expMonth = UInt((expDate?[0])!)
        let expYear = UInt((expDate?[1])!)

        checkoutVC.expMon = expMonth!
        checkoutVC.expYear = expYear!
        }
    }
}

@IBAction func checkout(_ sender: Any) {
    performSegue(withIdentifier: "checkout", sender: self)  
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

Code for view controller where the purchase is made: 购买代码的视图控制器代码:

import UIKit
import FirebaseAuth
import FirebaseDatabase
import Firebase
import Stripe

    class CheckoutController: UIViewController {

    let ref = Database.database().reference()

    @IBOutlet weak var feeLabel: UILabel!
    @IBOutlet weak var amountLabel: UILabel!

    var cardNumber = String()
    var cvc = String()
    var expMon = UInt()
    var expYear = UInt()

    @IBAction func purchase(_ sender: Any) {

        if Auth.auth().currentUser != nil {

            // Initiate the card
            let stripCard = STPCard()

            STPAPIClient.shared().createToken(withCard: stripCard, completion: { (token, error) -> Void in

                if error != nil {

                    print("There is an error")
                } 

                else {

                    // Send the card info to Strip to get the token
                    stripCard.number = self.cardNumber
                    stripCard.cvc = self.cvc
                    stripCard.expMonth = UInt(self.expMon)
                    stripCard.expYear = UInt(self.expYear)

                    let alert = UIAlertController(title: "Your Stripe token is " + (token?.tokenId)!, message: "", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                    alert.addAction(defaultAction)
                    self.present(alert, animated: true, completion: nil)
                    print(token!)
                }
            })

        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    let user = Auth.auth().currentUser
        let userID: String = (user?.uid)!

        if user != nil {

      let totalRef = ref.child("users/\(userID)").child("Total")
          totalRef.observeSingleEvent(of: .value, with: { (snapshot) in
            let cost = snapshot.value as! Int
            self.totalLabel.text = "\(cost) bookies"

            let total = (Double(cost) * 1.35) + 1.39

            self.amountLabel.text = "$\(total)"
        }) 
    }
}

The problem is that you're submitting a blank STPCard. 问题是您要提交空白的STPCard。 You are calling the createToken method without setting any of the fields on the card. 您在调用createToken方法时未设置卡上的任何字段。 For some reason, it looks like you're only setting the card fields in the Completion block after you've gotten a token. 出于某种原因,您似乎只是在获得令牌后才在“完成”块中设置卡片字段。 You need to move these lines: 您需要移动以下行:

 stripCard.number = self.cardNumber
 stripCard.cvc = self.cvc
 stripCard.expMonth = UInt(self.expMon)
 stripCard.expYear = UInt(self.expYear)

up before you make the call to createToken. 在调用createToken之前先进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM