#tarunmv30

1 messages · Page 1 of 1 (latest)

west slateBOT
final fossil
#

👋 How can I help?

heady breach
#

Im creating an online food orrdering app. Ive successfully implemented all the stripe functionality that was required besides adding a $5 fee for delivery orders.

#

im trying to send the boolean value in the post request but im hitting this error

#

can i send my server side function + client side function

final fossil
heady breach
#

Just a moment

#
  const amount = items.reduce((previous, current) => {
    return previous + current.price;
  }, 0);

  // Add the delivery fee if isForDelivery is true
  const totalAmount = isForDelivery ? amount + 500 : amount;

  const total = Math.round(totalAmount * 109);
  // Check that the total price is greater than or equal to $0.50 USD for testing purposes
  if (total < 50) {
    throw new Error('Amount must be at least $0.50 USD');
  }

  const fee = Math.round(total * 0.1);

  return {
    total: total,
    fee: fee
  };
};




app.post("/create-payment-intent/:userId", async (req, res) => {
  const userId = req.params.userId;
  const items = req.body;
  const isForDelivery = req.body.isForDelivery; // Assuming the isForDelivery property is present in the request body
  const { total, fee } = calculateOrderAmount(items, isForDelivery);

  const userDoc = await admin.firestore().collection("users").doc(userId).get();

  const customer = await stripe.customers.retrieve((userDoc.data().stripeCustomerId), {
    stripeAccount: 'acct_1MsyJPCWAlRghLO7',
  });

  const ephemeralKey = await stripe.ephemeralKeys.create(
    { customer: customer.id },
    { apiVersion: '2020-08-27', stripeAccount: 'acct_1MsyJPCWAlRghLO7' }
  );

  const paymentIntent = await stripe.paymentIntents.create({
    amount: total,
    currency: 'usd',
    application_fee_amount: fee,
    customer: customer.id,
    payment_method: req.body.payment_method_id, 
    setup_future_usage: 'on_session',
    automatic_payment_methods: {
      enabled: true,
    },
  }, {
    stripeAccount: 'XXXXXXWAlRghLO7',
  });
  
  res.send({
    customer: customer.id,
    ephemeralKey: ephemeralKey.secret,
    paymentIntent: paymentIntent.client_secret,
    publishableKey: 'pk_test_5XXXXXXXXXXXX
tmLvaUMn0KrXsbFVnqVROCRere3kLrAQnKOT2Uepb5fRqv34vjgNAArl8wzPwWd00OoOZlDFj' // replace with your own publishable key
  });
});
final fossil
#

What's the issue and error?

heady breach
#

One moment, im not even getting logs for when i test my payments anymore

#

That is my server side code^

#
    func preparePaymentSheet(cart: [MenuItem], isForDelivery: Bool) {
        let paymentRequest = PaymentRequest(cart: cart, isForDelivery: isForDelivery)

        do {
            let jsonData = try JSONEncoder().encode(paymentRequest)

            if let userId = Auth.auth().currentUser?.uid {
                let url = URL(string: "https://us-central1-neilsurbanoven.cloudfunctions.net/stripe/create-payment-intent/\(userId)")!
                var request = URLRequest(url: url)
                request.httpMethod = "POST"
                request.setValue("application/json", forHTTPHeaderField: "Content-Type")
                request.httpBody = jsonData

                let task = URLSession.shared.dataTask(
                    with: request,
                    completionHandler: { (data, _, _) in
                        guard let data = data,
                              let json = try? JSONSerialization.jsonObject(with: data, options: [])
                                as? [String: Any],
                              let customerId = json["customer"] as? String,
                              let customerEphemeralKeySecret = json["ephemeralKey"] as? String,
                              let paymentIntentClientSecret = json["paymentIntent"] as? String,
                              let publishableKey = json["publishableKey"] as? String
                        else {
                            print("There was an error with the data / specifically on the request sending the data.")
                            return
                        }

                        
#

my function is printing this error

#

print("There was an error with the data / specifically on the request sending the data.")

#

I dont think its properly able to send the cart / isForDelivery Bool to the server so stripe isnt getting alerted

final fossil
#

Has the payment intent been created successfully?

heady breach
#

How do i check this?

final fossil
#

You can put the logs at your server and check if a payment intent ID is created successfully. If a payment intent is created successfully, stripe.paymentIntents.create will return the payment intent ID

heady breach
#

so I fixed the issue somewhat

#

now the problem im having is that instead of adding 5 dollars the math is coming out really off

final fossil
#

What are the expected and actual numbers? Can you share the Payment Intent ID (pi_xxx)?

heady breach
#

yes one second

#

req_kM3UNIGksmbV3S

#

the actual amount is supposed to be approximately $15

final fossil
#

I'd recommend checking your calculateOrderAmount to identify the price and sum to understand why the final total isn't as intended

heady breach
#

can i share a screen recording with you my function seems right

final fossil
#

This is outside of Stripe as we don't know the prices of your product and how you add them up

heady breach
#

when the order is not for delivery the total is correct

#

when it is for delievery and its the same order the math is way off

#
  const amount = items.reduce((previous, current) => {
    return previous + current.price;
  }, 0);

  // Add the delivery fee if isForDelivery is true
  const totalAmount = isForDelivery ? amount + 500 : amount;

  const total = Math.round(totalAmount * 109);
  // Check that the total price is greater than or equal to $0.50 USD for testing purposes
  if (total < 50) {
    throw new Error('Amount must be at least $0.50 USD');
  }

  const fee = Math.round(total * 0.1);

  return {
    total: total,
    fee: fee
  };
};```
#

isnt + 500 in stripe equivalent to $5?

final fossil
#

Your server sent us the value. Stripe didn't compute or modify them