簡體   English   中英

提供的條紋無效的 API 密鑰:使用 express node.js 未定義

[英]Stripe Invalid API Key provided: undefined with express node.js

我正在為 Stripe 支付 api 苦苦掙扎。 當我在填寫數據和卡號后單擊按鈕時,它進入支付成功頁面,但控制台上有錯誤。 它說提供了Invalid API Key provided: undefined

在此處輸入圖片說明

另外,當我檢查條紋儀表板時,它說沒有付款方式。 在此處輸入圖片說明

在此處輸入圖片說明

Stripe 建議我使用付款方式,但在我的代碼上有付款方式。 我不知道是什么問題。

這是我的代碼

import React from 'react';
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';

//make the card elements 
const stripePromise = loadStripe(`${process.env.PUBLISHABLE_KEY}`);
console.log(stripePromise);
const CheckoutFormWrap = ({ children }) => {
  return (
    <div>
      <Elements stripe={stripePromise}>{children}</Elements>
    </div>
  );
};

CheckoutForm.js 
import React, { useState } from 'react';
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
import BillingDetailsFields from './BillingDetailForm';
import axios from 'axios';
import styled from 'styled-components';

const CheckoutForm = ({ price, onSuccessfulCheckout }) => {
  const [isProcessing, setProcessingTo] = useState(false);
  const [checkoutError, setCheckoutError] = useState();

  const stripe = useStripe();
  const elements = useElements();

  const handleCardDetailsChange = ev => {
    ev.error ? setCheckoutError(ev.error.message) : setCheckoutError();
  };
  const handleFormSubmit = async e => {
    e.preventDefault();
    const billingDetails = {
      name: e.target.name.value,
      email: e.target.email.value,
      };

    setProcessingTo(true);
    const cardElement = elements.getElement(CardElement);

 
    const { data: clientSecret } = await axios.post("http://localhost:5000/pay",
      {amount: price}
    );
    console.log(clientSecret);

    const paymentMethodReq =  await stripe.createPaymentMethod({
      type: 'card',
      card: cardElement,
      billing_details: billingDetails,
    });
    
    const confirmCardPayment = await stripe.confirmCardPayment(clientSecret,{
      payment_method: paymentMethodReq.paymentMethod,
    })
    onSuccessfulCheckout();
    console.log(confirmCardPayment);
    if (paymentMethodReq.error) {
      setCheckoutError(paymentMethodReq.error.message);
      setProcessingTo(false);
      return;
    }


  };
  return (
    <form  onSubmit={handleFormSubmit}>
      <div>
        <CheckoutTitle>Pay with</CheckoutTitle>
        <BillingDetailsFields />
      </div>
      <div>
        <CardElementContainer>
          <CardElement
            onChange={handleCardDetailsChange}
          />
        </CardElementContainer>
      </div>
      <div>
        <PayBtn disabled={isProcessing || !stripe}>
          {isProcessing ? 'Processing...' : `Confirm and Pay`}
        </PayBtn>
      </div>
    </form>
  );
};
export default CheckoutForm;

server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const stripe = require('stripe')(process.env.SECRET_KEY);

const app = express();
const port = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cors());

if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, 'client/build')));

  app.get('*', function (req, res) {
    res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
  });
}
app.listen(port, error => {
  if (error) throw error;
  console.log('server running on port' + port);
});

app.post('/pay', async (req, res) => {
  if (req.method === 'POST') {
    try {
      const { amount } = req.body;
      const paymentIntent = await stripe.paymentIntents.create({
        amount,
        currency: 'usd',
        payment_method_types: ['card_present'],
      });
      res.status(200).send(paymentIntent.client_secret);
    } catch (err) {
      res.status(500).json({ statusCode: 500, message: err.message });
    }
  } else {
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
});

有任何想法嗎?

我看到兩個問題:

  1. 您是否使用loadStripe和您的可發布密鑰初始化 Stripe.js ,並像文檔所說的那樣設置Elements提供程序?
  2. 在您調用confirmCardPayment您可能需要使用paymentMethodReq.paymentMethod.id因為createPaymentMethod 返回一個對象

請注意,您不需要進行兩次調用。 您可以將付款方式創建和付款意向確認合並為一個步驟, 如下所示

const result = await stripe.confirmCardPayment('{CLIENT_SECRET}', {
  payment_method: {
    card: cardElement,
    billing_details: billingDetails,
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM