如何使用 Firebase 云功能向客户端(Swift)发送条带响应
Posted
技术标签:
【中文标题】如何使用 Firebase 云功能向客户端(Swift)发送条带响应【英文标题】:How to send stripe response to client side(Swift) using Firebase cloud function 【发布时间】: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';
【问题讨论】:
【参考方案1】:基于Franks's post here,我决定等待 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 支付的人有所帮助
【讨论】:
以上是关于如何使用 Firebase 云功能向客户端(Swift)发送条带响应的主要内容,如果未能解决你的问题,请参考以下文章
CORS 阻止访问资源:如何在 Firebase 云功能中修复?
使用 firebase 云功能向非谷歌服务器发送 POST 请求