【发布时间】:2019-07-13 16:35:06
【问题描述】:
我正在使用 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.js swift firebase google-cloud-functions stripe-payments