【发布时间】: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