【发布时间】:2021-05-12 15:54:39
【问题描述】:
我正在开发一个有支付选项卡的应用程序,当我点击支付选项卡时,它会将我带到一个只有一个按钮的页面,当我单击该按钮时,它会将我带到条带结帐系统(https://stripe.com/docs/payments/checkout/client),一旦它处理了付款,它就会带我回到应用程序。我在 firebase 中有一个数据库,用于跟踪当前登录的用户是否已付费。如果当前用户未付款,我希望在付款成功完成后将该用户的数据库的成员资格字段从“假”更新为“真”。问题是,如果我在 try 块内完成付款后立即更新 db,则 db 不会更新,但如果我在 componentDidMount() func 内进行更新,我确实会看到对 db 所做的更改。我究竟做错了什么? func 是异步的事实是否会导致这里出现问题?如果我想在付款成功后更新数据库,那我该怎么做呢?
import React from 'react';
import firebase from "firebase/app";
import 'firebase/firestore';
import "firebase/database";
import { auth, database } from '../../firebase';
import { UserAndDbObjConsumer, UserAndDbObjContext } from '../../dbAndUserObjContext';
import { loadStripe } from '@stripe/stripe-js';
// Make sure to call `loadStripe` outside of a component’s render to avoid
// recreating the `Stripe` object on every render.
const stripePromise = loadStripe('test key here');
export default class Payment extends React.Component {
static contextType = UserAndDbObjContext;
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
const {user, database} = this.context;
// When i update my data below, it updates the firebase db and i can
// see the changes taking effect
// database.collection("userCollection").doc(user.uid).update({
// membership: true
// })
}
handleClick = async (event) => {
const {user, database} = this.context;
console.log("i am inside handle but outside try")
try {
// When the customer clicks on the button, redirect them to Checkout.
const stripe = await stripePromise;
const { error } = await stripe.redirectToCheckout({
lineItems: [{
price: 'price_1IF4cPAt4f9zG3h2hTG64agQ', // Replace with the ID of your price
quantity: 1,
}],
mode: 'payment',
successUrl: 'https://app.guideanalytics.ca/',
cancelUrl: 'https://guideanalytics.ca/termsofuse.html',
});
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `error.message`.
// When i update the firebase db here, than the changes on firebase dont take place
database.collection("userCollection").doc(user.uid).update({
membership: true
})
}
catch(e) {
console.log(e);
}
}
render() {
return (
<div>
<button role="link" onClick={(e) => this.handleClickTest()}>
Checkout
</button>
</div>
)
}
}
//Payment.contextType = Context;
【问题讨论】:
标签: reactjs firebase google-cloud-firestore stripe-payments