React Native 应用程序在构建模式下访问 Stripe 支付屏幕时意外崩溃

问题描述 投票:0回答:1

我在 React Native 中开发了一个应用程序,可以使用 Stripe 执行金融交易。下面的函数负责访问我开发的 Node.js 服务器的端点。没有什么复杂的事情,很简单。在模拟器中,我可以访问元素(支付屏幕)并在交易中获得成功,但在构建(预览模式)中,应用程序意外关闭,没有警告,也没有任何通知。下面是服务器和 React Native 的代码。

 const buy = async () => {
try {
  const finalAmount = amount;
  const response = await fetch('https://app-production.up.railway.app/buy', {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      coin: `App - ${priceList[selectedId].time_session}`,
      quantity: quantity,
      amount: finalAmount,
    }),
  });
  const data = await response.json();
  if (!response.ok) {
    return Alert.alert(data.message);
  }
  const initSheet = await stripe.initPaymentSheet({
    paymentIntentClientSecret: data.clientSecret,
    merchantDisplayName: "App",
  });
  if (initSheet.error) {
    return Alert.alert(initSheet.error.message);
  }
 
  const presentSheet = await stripe.presentPaymentSheet();
  if (presentSheet.error) {
    return Alert.alert(presentSheet.error.message);
  }

  Alert.alert("Payment successful!");
  addIncomeTransaction()
  // Update user data in Firestore
  const userRef = doc(db, 'users', userID);
  await updateDoc(userRef, {
    'user_billing.balance': totalCoins + amount,
    'user_billing.plan_aquisition': PlanAquired,
  });

  setTotalCoins(totalCoins + amount);
  setQuantity(1);
} catch (err) {
  Alert.alert("Error", err.message);
}
};

应用程序.tsx

return (
<StripeProvider publishableKey={process.env.EXPO_PUBLIC_STRIPE_KEY}>
<ReduxProvider store={Store}>
  <PaperProvider>
    <GestureHandlerRootView style={{ flex: 1 }} onLayout={onLayoutRootView}>
      <Router />
    </GestureHandlerRootView>
  </PaperProvider>
</ReduxProvider>
</StripeProvider>

);

下面的服务器

require("dotenv").config();
const express = require("express");
const app = express();
const Stripe = require("stripe");
const stripe = Stripe(process.env.STRIPE_SECRET_KEY);
const cors = require("cors");
const PORT = process.env.PORT || 4242;

app.use("/stripe", express.raw({ type: "*/*" }));
app.use(express.json());
app.use(cors({
origin: 'https://App-production.up.railway.app/'
}));


app.post("/buy", async (req, res) => {
 try {
 // Getting data from client
 let { coin, quantity, amount } = req.body;
 // Simple validation
 if (!coin || !quantity || !amount)
  return res.status(400).json({ message: "Invalid data, try again" });
  amount = parseInt(amount);

// Initiate payment
const paymentIntent = await stripe.paymentIntents.create({
amount: Math.round(amount * 100) / 10 * 10, // Amount in cents ex: 10.90 -> 1090  
currency: 'brl',
payment_method_types: ["card"],
metadata: { coin, quantity, amount },
 });
// Extracting the client secret
const clientSecret = paymentIntent.client_secret;
// Sending the client secret as response
res.json({ message: "Initializing payment", clientSecret });
 } catch (err) {
 // Catch any error and send error 500 to client
 console.error(err);
 res.status(500).json({ message: "Internal server error." });
 }
 });

  // Webhook endpoint
  app.post("/stripe", async (req, res) => {
 // Get the signature from the headers
 const sig = req.headers["stripe-signature"];

 let event;

  try {
   // Check if the event is sent from Stripe or a third party
   // And parse the event
   event = await stripe.webhooks.constructEvent(
    req.body,
    sig,
    process.env.STRIPE_WEBHOOK_SECRET
    );
    } catch (err) {
    // Handle what happens if the event is not from Stripe
    console.log(err);
   return res.status(400).json({ message: err.message });
   }
  // Event when a payment is initiated
 if (event.type === "payment_intent.created") {
  console.log(`${event.data.object.metadata.coin} payment initated!`);
 }
 // Event when a payment is succeeded
 if (event.type === "payment_intent.succeeded") {
  // fulfilment
  console.log(`${event.data.object.metadata.coin} payment successfuly!`);
 }
res.json({ ok: true });
 });

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
android node.js react-native express stripe-payments
1个回答
0
投票

您是否弄清楚问题是什么以及如何解决它的任何线索?

© www.soinside.com 2019 - 2024. All rights reserved.