如何使用Firebase云功能将条带响应发送到客户端(Swift)

时间:2019-02-20 04:07:40

标签: node.js swift firebase google-cloud-functions stripe-payments

我正在使用Stripe和Firebase作为后端制作类似Airbnb的iOS应用。我正在关注这份文件。 https://medium.com/firebase-developers/go-serverless-manage-payments-in-your-apps-with-cloud-functions-for-firebase-3528cfad770
如文档所述,这是我到目前为止所做的工作流程。(假设用户要购买东西)
1。用户将付款信息(例如金额货币和卡令牌)发送到Firebase实时数据库。
2。 Firebase触发了一个功能,该功能将充电请求(stripe.charge.create)发送到Stripe。
3。得到响应后,将其写回Firebase数据库。如果响应失败,则将错误消息写入数据库(请参见index.js中的userFacingMessage函数)
4。在客户端(Swift)中,观察Firebase数据库以检查响应。
5.如果响应成功,则向用户显示成功消息。如果存在任何错误,例如(由于信用卡过期而导致付款失败),则向用户显示失败消息(还显示“请重试”消息)

我猜这是不正确的方法因为我认为用户只要Firebase从Stripe获得响应,用户就应该知道响应(成功还是失败),换句话说,客户端(Swift)应该在获得响应后立即获得响应,然后再写回Firebase数据库?有人知道如何将响应发送到客户端吗?
任何帮助将不胜感激

ChargeViewController.swift(客户端)

  func didTapPurchase(for amountCharge: String, for cardId: String) {
    print("coming from purchas button", amountCharge, cardId)

    guard let uid = Auth.auth().currentUser?.uid else {return}

    guard let cardId = defaultCardId else {return}
    let amount = amountCharge
    let currency = "usd"

    let value = ["source": cardId, "amount": amount, "currency": currency] as [String: Any]

    let ref = Database.database().reference().child("users").child(uid).child("charges")
    ref.childByAutoId().updateChildValues(value) { (err, ref) in
        if let err = err {
            print("failed to inserted charge into db", err)
        }

        print("successfully inserted charge into db")

       //Here, I want to get the response and display messages to user whether the response was successful or not.

    }

}

index.js(云函数)语言:node.js

exports.createStripeCharge = functions.database
.ref(‘users/{userId}/charges/{id}’)
.onCreate(async (snap, context) => {
const val = snap.data();
try {
// Look up the Stripe customer id written in createStripeCustomer
const snapshot = await admin.database()
.ref(`users/stripe/${context.params.userId}/stripe_customer_id`)
.once('value');

const snapval = snapshot.data();
const customer = snapval.stripe_customer_id;
// Create a charge using the pushId as the idempotency key
// protecting against double charges
const amount = val.amount;
const idempotencyKey = context.params.id;
const charge = {amount, currency, customer};
if (val.source !== null) {
   charge.source = val.source;
}
const response = await stripe.charges
    .create(charge, {idempotency_key: idempotencyKey});
// If the result is successful, write it back to the database
//*I want to send this response to the client side but not sure how if I can do it nor not*
return snap.ref.set(response);
} catch(error) {
    await snap.ref.set(error: userFacingMessage(error));
}
});
    // Sanitize the error message for the user
function userFacingMessage(error) {
  return error.type ? error.message : 'An error occurred, developers have been alerted';
}

1 个答案:

答案 0 :(得分:0)

基于Franks's post here,我决定等待Firebase数据库中的更改。下面是工作流程和代码(index.js文件没有变化):

1.用户在/ users / {userId} / charges路径中将付款信息(例如币种和卡令牌)发送到Firebase实时数据库
2. Firebase触发一个功能,该功能将充电请求(stripe.charge.create)发送到Stripe。
3.获得响应后,将其写回到Firebase数据库。如果响应失败,则将错误消息写入数据库(请参见index.js中的userFacingMessage函数)
4.在客户端(Swift)中,等待Firebase数据库中的更改,以使用Observe(.childChanged)检查响应是否成功(请参见Swift代码)
5.如果响应成功,则向用户显示成功消息。如果有任何错误,例如((由于信用卡过期导致付款失败),则向用户显示失败消息(还显示“请重试”消息)

ChargeViewController.swift

func didTapPurchase(for amountCharge: String, for cardId: String) {
print("coming from purchas button", amountCharge, cardId)

guard let uid = Auth.auth().currentUser?.uid else {return}

guard let cardId = defaultCardId else {return}
let amount = amountCharge
let currency = "usd"

let value = ["source": cardId, "amount": amount, "currency": currency] as [String: Any]

let ref = Database.database().reference().child("users").child(uid).child("charges")
ref.childByAutoId().updateChildValues(value) { (err, ref) in
    if let err = err {
        print("failed to inserted charge into db", err)
    }

    print("successfully inserted charge into db")

   //Here, Wait for the response that has been changed
   waitForResponseBackFromStripe(uid: uid)

  }

 }

func waitForResponseBackFromStripe(uid: String) {

    let ref = Database.database().reference().child("users").child(uid).child("charges")
    ref.observe(.childChanged, with: { (snapshot) in

        guard let dictionary = snapshot.value as? [String: Any] else {return}

        if let errorMessage = dictionary["error"] {
            print("there's an error happening so display error message")
            let alertController = UIAlertController(title: "Sorry:(\n \(errorMessage)", message: "Please try again", preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
            //alertController.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
            self.present(alertController, animated: true, completion: nil)
            return

        } else {
            let alertController = UIAlertController(title: "Success!", message: "The charge was Successful", preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
            self.present(alertController, animated: true, completion: nil)
        }
    }) { (err) in
        print("failed to fetch charge data", err.localizedDescription)
        return
    }
}

如果我在逻辑上做错了,请告诉我。但到目前为止对我有用 希望这对集成Firebase和Stripe付款的人有所帮助