gpt4 book ai didi

node.js - 如何使用 Firebase 云功能将 strip 响应发送到客户端(Swift)

转载 作者:行者123 更新时间:2023-11-28 07:30:49 25 4
gpt4 key购买 nike

我正在使用 Stripe 和 Firebase 作为后端制作类似 Airbnb 的 iOS 应用。我正在关注这个文档。 https://medium.com/firebase-developers/go-serverless-manage-payments-in-your-apps-with-cloud-functions-for-firebase-3528cfad770 .
正如文档所说,这是我到目前为止所做的工作流程。(假设用户想要购买东西)
1。用户向 Firebase 实时数据库发送付款信息,例如金额货币和卡 token )
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';
}

最佳答案

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

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

关于node.js - 如何使用 Firebase 云功能将 strip 响应发送到客户端(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54778686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com