首页 > 解决方案 > 如何使用 Firebase 云功能向客户端(Swift)发送条带响应

问题描述

我正在使用 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 收取费用请求(stripe.charge.create)。
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';
}

标签: node.jsswiftfirebasegoogle-cloud-functionsstripe-payments

解决方案


根据Franks 在此处的帖子,我决定等待 Firebase 数据库的更改。以下是工作流程和代码(index.js 文件没有变化):

1. 用户在 /users/{userId}/charges 路径中向 Firebase 实时数据库发送支付信息,例如金额货币和卡令牌
2。 Firebase 触发一个向 Stripe 发送收费请求(stripe.charge.create)的函数。
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 支付的人有所帮助


推荐阅读