【问题标题】:Hiding secret/publishable Stripe API keys in .env file, not working在 .env 文件中隐藏秘密/可发布的 Stripe API 密钥,不起作用
【发布时间】:2021-06-05 19:45:49
【问题描述】:

如何通过 .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,
        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;

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

【问题讨论】:

  • require('dotenv').config();放在const stripe = require('stripe')(process.env.REACT_APP_STRIPE_SECRET_KEY);上面如果你没有Dotenv,运行npm i dotenv
  • 我添加了 require('dotenv').config();并安装了 dotenv,不幸的是它仍然无法正常工作
  • 安装后有没有重启应用?
  • 是的,我什至重新启动了我的电脑
  • 你能把那些单引号改成双引号吗?例如REACT_APP_STRIPE_PUBLIC_KEY="pk_test_..."

标签: reactjs silverstripe stripe-payments


【解决方案1】:

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

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

require('dotenv').config();

【讨论】:

  • 我添加了 require('dotenv').config();在 stripe.js 文件的顶部,然后安装 dotenv (npm install dotenv)。然后我重新启动了我的项目,但不幸的是它仍然无法正常工作,还有其他我可以解决的问题吗?
  • 我看到了问题,您的 .env 文件在文件夹结构中应该与包含 require('dotenv').config(); 的文件处于同一级别所以有 2 个选项: 1. 将 .env 文件移动到 /server/src 文件夹 2. 将 server.js 移动到顶层,并在那里声明 require('dotenv').config()
  • 或者你可以尝试将“path”参数传递给配置选项:require('dotenv').config({ path: '../../.env' })
  • 你说得对,我需要在文件夹结构中将.env文件移动到同一级别,谢谢
【解决方案2】:

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

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

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

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

【讨论】:

  • 我删除了所有单引号并运行:npm install dotenv。由于某种原因仍然无法正常工作...
猜你喜欢
  • 2020-02-10
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
  • 2022-12-17
  • 2014-03-19
  • 2020-03-04
  • 2022-07-06
  • 2021-04-30
相关资源
最近更新 更多