在 .env 文件中隐藏 secret/publishable Stripe API 键,不起作用

Hiding secret/publishable Stripe API keys in .env file, not working

如何通过 .env 文件隐藏我的 secret/publishable 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,
        source,
        name: customerName,
        address,
      });
    }

    const charge = await stripe.charges.create({
      amount,
      currency: 'usd',
      source,
      receipt_email,
      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;

PaymentForm(可发布密钥)

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, backStep, nextStep, setQty }) {
  return (
    <Elements stripe={stripePromise}>
      <Review />
      <br />
      <br />
      <CheckoutForm shippingData={shippingData} nextStep={nextStep} backStep={backStep} setQty={setQty} />
    </Elements>
  );
}

export default PaymentForm;

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

因为它会在您的计算机上查找环境变量。 要使用 .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 软件包。当我在 google 云

中部署我的应用程序时遇到同样的问题时发生在我身上
const Stripe = require("stripe);
exports.function = async ()=>{
    const stripe = Stripe(process.env.STRIPE_SECRET_KEY);
}