简体   繁体   English

条带/重定向结账有问题

[英]having problems with stripe/ redirecttocheckout

i have been trying to understand stripe for quite a while now.我一直试图理解条纹很长一段时间了。 the major problem i am having is that i am a front end developer (with about a year of experience) and while i have some node.js/backend experience it is simply not enough to handle server processing of payments.我遇到的主要问题是我是一名前端开发人员(有大约一年的经验),虽然我有一些 node.js/后端经验,但它根本不足以处理服务器处理付款。 i am going for the JAMstack serverless function approach using netlify.我打算使用 netlify 的 JAMstack 无服务器 function 方法。 and thus far everything seems to be working out EXCEPT right at redirect to checkout i am getting the error "stripe.redirectToCheckout is not a function"到目前为止,一切似乎都在进行,除了重定向到结帐时我收到错误“stripe.redirectToCheckout 不是函数”

here is some of my code:这是我的一些代码:

const inventory = require('./data/products.json');

exports.handler = async (event) => {
  const { sku, quantity } = JSON.parse(event.body);
  const product = inventory.find((p) => p.sku === sku);
  const validatedQuantity = quantity > 0 && quantity < 2 ? quantity : 1;

  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    billing_address_collection: 'auto',
    shipping_address_collection: {
      allowed_countries: ['US'],
    },
    success_url: `${process.env.URL}/success`,
    cancel_url: process.env.URL,
    line_items: [
      {
        name: 'bitch',
        currency:'USD',
        amount: 299,
        quantity: validatedQuantity,
      },
    ],
  });

  return {
    statusCode: 200,
    body: JSON.stringify({
      sessionId: session.id,
      publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
    }),
  };
};

^^^^this is where i create the checkout through a serverless function although it took some time i have been able to create a lambda function through netlify, hide my public and private keys, create a stripe element, but i am just so confused as to why i am getting this error... ^^^^this is where i create the checkout through a serverless function although it took some time i have been able to create a lambda function through netlify, hide my public and private keys, create a stripe element, but i am just so confused至于我为什么会收到这个错误...

blow is where the error seems to be打击似乎是错误的地方

//client sides
import Stripe from 'stripe'

export async function handleFormSubmission(event) {
  event.preventDefault();

  const form = new FormData(event.target);

  const data = {
    sku: form.get('sku'),
    quantity: Number(form.get('quantity')),
  };


  const response = await fetch('/.netlify/functions/create-checkout', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  }).then((res) => res.json());

  const stripe=Stripe(response.publishableKey);
  const {err}=await stripe.redirectToCheckout({
    sessionId:response.sessionId
  })


  if(err){
    console.log(err)
  }
}

also if it is any help here is where i am calling the function (handleformsubmit or whatever)另外,如果这里有任何帮助,我在哪里调用 function (handleformsubmit 或其他)

import React from 'react'
import {loadStripe} from "@stripe/stripe-js"
import './Checkout.css'
import {useState} from 'react'
import {Elements,
CardElement,
useStripe,
useElements} from '@stripe/react-stripe-js'
import axios from 'axios'
import {loadProducts} from './load-products'
import {handleFormSubmission} from './stripe-purchase'



const stripePromise=loadStripe(`${process.env.STRIPE_}`)

const CheckoutForm=()=>{

  const stripe=useStripe()
  const elements=useElements()
  const handleSubmit=async(e)=>{

    e.preventDefault()
    if (!stripe || !elements) {
    // Stripe.js has not loaded yet. Make sure to disable
    // form submission until Stripe.js has loaded.
    return;
  }
  // Get a reference to a mounted CardElement. Elements knows how
   // to find your CardElement because there can only ever be one of
   // each type of element.
  const cardElement = elements.getElement(CardElement);

    const {error, paymentMethod}=await stripe.createPaymentMethod({
      type:'card',
      card:cardElement
    })

    loadProducts();

  }

  return (
    <form onSubmit={handleFormSubmission} method='POST'>
      <img className='checkoutImage' src='./logo2.png' />
      <label  class="ml-2  font-bold text-blue-700 text-md">
Enter card details below:
                        </label>
      <fieldset className="my-2 FormGroup">

         <div className="FormRow">
         <CardElement options={{
     style: {
       base: {
         fontSmoothing: 'antialiased',
         fontWeight: 900,
         iconColor: '#60A5FA',
         fontSize: '30px',
         color: '#374151',
         '::placeholder': {
           color: '#3182ce',
         },
       },
       invalid: {
         iconColor: '#EF4444',
         color: '#DC2626',
       },
       complete:{
         iconColor:'green',
         color: 'green',
       }
     },
   }}/>
         </div>
       </fieldset>


<div className='checkoutbuttonContainer'>
            <button type="submit" className="scoreButtons scoreButtonGrey flex justify-center rounded-md border border-gray-300 bg-pink-600 shadow-sm px-4 py-2 bg-white text-base font-medium text-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 hover:bg-pink-500 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                Submit Payment <span className='priceLine'></span> <span className='price'> </span>
                </button>
                </div>
                </form>

  )
}

const StripeSetup = () => {
  return (
    <div><Elements stripe={stripePromise}><CheckoutForm /></Elements></div>
  )
}

export default StripeSetup

this is the first time in a while i have felt really overwhelmed by new material.这是一段时间以来我第一次对新材料感到不知所措。 im not even sure if i'm learning at a proper pace anymore nor even learning as much as just copying in code i find online lol... but this did take a good amount of work on my end nonetheless.我什至不确定我是否正在以适当的速度学习,甚至不知道是否像复制我在网上找到的代码一样学习大声笑……但这确实需要我做大量的工作。 would really love if someone could help.如果有人可以提供帮助,我会很高兴。 BTW i am now realizing that i created stripe elements etc which i don't even know if are necessary when using redirect to checkout as this is supposed to lead the client to a stripe checkout?顺便说一句,我现在意识到我创建了条带元素等,我什至不知道在使用重定向结帐时是否有必要,因为这应该引导客户进行条带结帐? can someone clarify all this for me.有人可以为我澄清这一切。 and please help if they can!如果可以,请提供帮助! thanks so much in advance提前非常感谢

ONE last thing i wanted to say.我想说的最后一件事。 i do not need a cart, products listing or anything.我不需要购物车、产品列表或任何东西。 this is a one time payment for 2.99 and it will lead to the next page is the user submits the payment.这是 2.99 的一次性付款,它将导致下一页是用户提交付款。 not sure if that changes anything but figured the more details the better不确定这是否会改变任何东西,但认为越详细越好

Problem was in AWFUL documentation as well as netlify's instructions.问题出在 AWFUL 文档以及 netlify 的说明中。

i needed to call loadstripe again first:我需要先再次调用 loadstripe:

  const stripe=await loadStripe(response.publishableKey);
  const {err}=await stripe.redirectToCheckout({
    sessionId:response.sessionId
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM