在 .env 文件中隐藏秘密/可发布的 Stripe API 密钥,不起作用

问题描述

如何通过 .env 文件隐藏我的秘密/可发布 Stripe API 密钥?看起来我正确地遵循了说明,但它不起作用。当我直接列出密钥时,它可以工作,但在通过 .env 文件时却无效。

下面是我的 .env 文件

.env

REACT_APP_STRIPE_PUBLIC_KEY='pk_test_***hidden,but full key displayed here in my original code***'
REACT_APP_STRIPE_SECRET_KEY='sk_test_***hidden,but full key displayed here in my original code***'

stripe.js(密钥)

const stripe = require('stripe')(process.env.REACT_APP_STRIPE_SECRET_KEY);

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

    const { data } = await stripe.customers.list({ email: receipt_email });
    const customer = data.length ? data.find((c) => c.email === receipt_email) : null;

    let nCustomer;
    if (customer && customer.id) {
      nCustomer = await stripe.customers.update(customer.id,{
        default_source: customer.default_source,});
    } else {
      nCustomer = await stripe.customers.create({
        email: receipt_email,name: customerName,});
    }

    const charge = await stripe.charges.create({
      amount,currency: 'usd',description: `Product: ${title}`,customer: nCustomer.id,});

    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;

付款表(可发布密钥)

import React,{ useState } from 'react';
import { Typography,Button,Divider } from '@material-ui/core';
import {
  Elements,CardElement,ElementsConsumer,useStripe,useElements,} from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import axios from 'axios';

import { getTotal } from '../../helpers/helperTools';


import Review from './Review';

const stripePromise = loadStripe(process.env.REACT_APP_STRIPE_PUBLIC_KEY);

const CheckoutForm = ({ shippingData,backStep,nextStep,setQty }) => {
  const stripe = useStripe();
  const elements = useElements();
  const handleSubmit = async (event) => {
    event.preventDefault();
    if (!stripe || !elements) {
      return;
    }

    const storageItems = JSON.parse(localStorage.getItem('product'));
    const products = storageItems || [];

    const totalPrice = getTotal(products);
    let productTitle = '';

    products.map((item,index) => {
      productTitle = `${productTitle} | ${item.title}`;
    });

    const cardElement = elements.getElement(CardElement);
    // Instead of token we need to attach source here
    // because source has more payments options available
    const { error,source } = await stripe.createSource(cardElement);
    console.log(error,source);
    const order = await axios.post('http://localhost:7000/api/stripe/charge',{
      amount: totalPrice * 100,source: source.id,receipt_email: shippingData.email,title: productTitle,customerName: `${shippingData.firstName} ${shippingData.lastName}`,address: {
        city: shippingData.City,country: shippingData.shippingCountry,line1: shippingData.address1,postal_code: shippingData.ZIP,state: shippingData.shippingState,},});

    if (error) {
      console.log('[error]',error);
    } else {
      console.log('[PaymentMethod]',order);
      localStorage.setItem('product',JSON.stringify([]));
      nextStep();
      setQty({quantity: 0});
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <CardElement
        options={{
          style: {
            base: {
              fontSize: '16px',color: '#424770','::placeholder': {
                color: '#aab7c4',invalid: {
              color: '#9e2146',}}
      />
      <div style={{ display: 'flex',justifyContent: 'space-between' }}>
        <Button variant='outlined' onClick={backStep}>
          Back
        </Button>
        <Button type='submit' variant='contained' disabled={!stripe} color='primary'>
          Pay
        </Button>
      </div>
    </form>
  );
};

function PaymentForm({ shippingData,setQty }) {
  return (
    <Elements stripe={stripePromise}>
      <Review />
      <br />
      <br />
      <CheckoutForm shippingData={shippingData} nextStep={nextStep} backStep={backStep} setQty={setQty} />
    </Elements>
  );
}

export default PaymentForm;

下面是我的文件结构截图:

rt

解决方法

因为它会在您的计算机上查找环境变量。 要使用 .env 文件中的变量,请使用 dotenv(https://www.npmjs.com/package/dotenv) 等库

这个库的使用非常简单,只需在你的主 server.js 文件中提供下一行:

require('dotenv').config();
,

从 .env 文件变量值中删除单引号:

`REACT_APP_STRIPE_PUBLIC_KEY=pk_test_隐藏,但完整的密钥显示在我的原始代码中

REACT_APP_STRIPE_SECRET_KEY=sk_test_隐藏,但完整的密钥显示在我的原始代码中`

如果仍然无法正常工作,请在您的机器中安装 dot-env 包。当我在谷歌云中部署的应用程序遇到同样问题时发生在我身上