简体   繁体   English

使用 Stripe 接受在线支付

[英]Accepting online payments with Stripe

So It is my first time using Stripe, the thing I am trying to do is this.所以这是我第一次使用 Stripe,我想做的就是这个。 I have created a backend for it for testing purposes.我为它创建了一个后端用于测试目的。 But I am having a problem, when I click on the button pay, I am getting this error in the console Uncaught (in promise) IntegrationError: You must provide a Stripe Element or a valid token type to create a Token.但是我遇到了一个问题,当我单击按钮付款时,我在控制台中收到此错误Uncaught (in promise) IntegrationError: You must provide a Stripe Element or a valid token type to create a Token. . . What is causing this error?是什么导致了这个错误?

Server.js服务器.js


require("dotenv").config({ path: "./config.env" });
const express = require("express");
const app = express();
const bodyParser = require('body-parser')
const postCharge = require('./routes/stripe')
const router = express.Router()
const cors = require("cors")

app.use(express.json());
app.use(cors());


router.post('/stripe/charge', postCharge)
router.all('*', (_, res) =>
  res.json({ message: 'please make a POST request to /stripe/charge' })
)
app.use((_, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  )
  next()
})
app.use(bodyParser.json())
app.use('/payment',router)

app.get('*', (_, res) => {
  res.sendFile(path.resolve(__dirname, '../audible/public/index.html'))


const PORT = process.env.PORT || 5000;

const server = app.listen(PORT, () =>
  console.log(`Sever running on port ${PORT}`)
);

Stripe.js条纹.js

const stripe = require('stripe')(process.env.STRIPE_SECRET_TEST)

async function postCharge(req, res) {
  try {
    const { amount, source, receipt_email } = req.body

    const charge = await stripe.charges.create({
      amount,
      currency: 'usd',
      source,
      receipt_email
    })

    if (!charge) throw new Error('charge unsuccessful')

    res.status(200).json({
      message: 'charge posted successfully',
      charge
    })
  } catch (error) {
    res.status(500).json({
      message: error.message
    })
  }
}

module.exports = postCharge

Payment Form付款表格

import React,{useContext, useState} from 'react'
import {CardElement, useStripe, useElements } from"@stripe/react-stripe-js"
import { CartContext } from '../../context/cart'
import axios from 'axios'
import {  useHistory } from "react-router-dom";


const CARD_OPTIONS={
    base: {
        color: '#303238',
        fontSize: '16px',
        fontFamily: '"Open Sans", sans-serif',
        fontSmoothing: 'antialiased',
        '::placeholder': {
          color: '#CFD7DF',
        },
      },
      invalid: {
        color: '#e5424d',
        ':focus': {
          color: '#303238',
        },
      },
}
const PaymentForm = () => {
  const { total} = useContext(CartContext)
  const stripe = useStripe();
  const [receiptUrl, setReceiptUrl] = useState('')
  const history = useHistory()
  const {clearCart} = useContext(CartContext)
  const elements = useElements()

  const handleSubmit = async event => {
    event.preventDefault()
    const cardElement = elements.getElement(CardElement);
    const { token } = await stripe.createToken()

    const order = await axios.post('http://localhost:5000/api/stripe/charge', {
      amount: 1000,
      source: token,
      card: cardElement,
      receipt_email: 'customer@example.com'
      
    })
    setReceiptUrl(order.data.charge.receipt_url)
  }
  if (receiptUrl){
    history.push('/');
    clearCart();
    return (
      <div className="success">       
        <h2>Payment Successful!</h2>
      </div>
    )
  }

    return (
        <>  
         <form onSubmit={handleSubmit}>
             <fieldset className='form_group'>
                <div className='formRow'>
                    <CardElement options={CARD_OPTIONS} />
                </div>
             </fieldset>
                <button type='submit' className=''>Pay</button>
                <h3>
                    order total : <span> ${total}</span>
                </h3>
         </form>
        </>
    )
  }  



export default PaymentForm

Stripe Container条纹容器

import React from 'react'
import {loadStripe} from '@stripe/stripe-js'
import {Elements, } from '@stripe/react-stripe-js'
import PaymentForm from './PaymentForm'
const PUBLIC_KEY="pk_test_51IaINYEqJWuHZaMS8NbdFT8M7ssdvFXOqBO8gwn1MjQCJ9Mq5kYdraTFG4Y28i9xLtaWKJanVLLbjlrduQKHv00uJ0WbJnu"

const stripeTestPromise = loadStripe(PUBLIC_KEY)
const StripeContainer = () => {
    return (
        <Elements stripe={stripeTestPromise}>
            <PaymentForm   />
        </Elements>
    )
}
export default StripeContainer

Instead of using Tokens & Charges for a new integration, I'd suggest using the newer Payment Intents & Payment Methods APIs, following this guide to accept a payment .我建议不要使用 Tokens & Charges 进行新的集成,而是使用更新的 Payment Intents & Payment Methods API,按照本指南接受付款

It also looks like you're using the deprecated react-stripe-elements library ( deprecation notice ), which has be replaced with the @stripe/react-stripe-js library ( github , docs ).看起来您正在使用已弃用的react-stripe-elements库( 弃用通知),该库已替换为@stripe/react-stripe-js库( github文档)。

In either case you need to make sure you initialize Stripe.js with a provider.无论哪种情况,您都需要确保使用提供程序初始化 Stripe.js。 Using the newer library that looks like this ( docs ):使用看起来像这样的新库(文档):

const stripePromise = loadStripe('pk_test_123');

const App = () => {
  return (
    <Elements stripe={stripePromise}>
      <MyCheckoutForm />
    </Elements>
  );
};

If you want to use the older library, the provider works like this ( old docs ):如果您想使用较旧的库,提供程序的工作方式如下( 旧文档):

import {StripeProvider} from 'react-stripe-elements';
import MyStoreCheckout from './MyStoreCheckout';

const App = () => {
  return (
    <StripeProvider apiKey="pk_test_12345">
      <MyStoreCheckout />
    </StripeProvider>
  );
};

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

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