我试图使用Stripe API允许用户在我的应用程序中购买我的erc 20令牌。但我得到了这个错误。我已经尝试使用nonce,但没有帮助仍然得到相同的错误。
我的前端:
import {useState} from 'react';
import{loadStripe} from '@stripe/stripe-js';
import axios from 'axios';
export default function payment(){
const [numberOfTokens, setNumberOfTokens]=useState()
const [sessionId, setSessionId]=useState(null);
const[pricePerToken, setPricePerToken] = useState(1.68);
const [nonce, setNonce] = useState();
const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY);
const totalAmountCalculation=()=>{
const feePercent = 3;
const totalFee = ( Number(numberOfTokens) * feePercent)/100;
const totalAmount =(Number(numberOfTokens) + totalFee)* pricePerToken;
return totalAmount
}
const handleBuyWithUsd=async(e)=>{
e.preventDefault();
const amt = totalAmountCalculation();
const amount = Math.round(amt*100)
console.log(Math.round(amt*100))
const dat = {
amount: amount,
quantity: 1
}
const stripe = await stripePromise;
//Send a request to the API route to create a new Checkout session
const response = await axios.post('/api/blockchain/buy_token_usd ',
dat)
console.log("response",response)
//Redirect the user to checkout page
const result = await stripe.redirectToCheckout({
sessionId: response.data.sessionId,
});
if(result){
setNonce(response.headers.nonce)
}
if(result.error){
console.log("error",result.error.message)
}
}
return(
<div>
<label>Number of Tokens</label>
<input type='text' placeholder='Number of Tokens' onChange={(event) => setNumberOfTokens(event.target.value)}></input>
<button onClick={handleBuyWithUsd}>Buy</button>
<script nonce={nonce} src="https://js.stripe.com/v3/"></script>
</div>
)
}
我的后台:
import Stripe from 'stripe';
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
export default async function handler(req,res){
if(req.method == 'POST'){
try{
// passing the total amount of the token Purchased
const amount= req.body.amount;
// Create a new Checkout session with Stripe API
const session = await stripe.checkout.sessions.create({
payment_method_types:['card'],
line_items:[
{
price_data: {
currency: 'usd',
unit_amount: amount,
product_data: {
name: 'My Token',
description: 'ERC20 token',
},
},
quantity: 1,
},
],
mode: 'payment',
success_url:'http://localhost:3000',
cancel_url:'http://localhost:3000/fail',
});
const nonce = Buffer.from(session.id).toString('base64');
res.setHeader('Content-Security-Policy', `default-src 'self'; script-src 'self' 'unsafe-inline' 'nonce-${nonce} '`);
res.status(200).json({ sessionId: session.id });
}
catch(error){
res.status(500).json({ error: error.message });
}
}
}
错误:
拒绝执行内联脚本,因为它违反了以下内容安全策略指令:“script-src 'self'”。启用内联执行需要'unsafe-inline'关键字、hash('sha 256-DrqjFVdP 4 HVgC 3QkAUQz 0 r5 qIO 2 JWzu 68 ZgFf 2UKHrk =')或nonce('nonce-...')。
1条答案
按热度按时间7xzttuei1#
我认为你有两个主要的选择:
res.status(200).json({ sessionURL: session.url });
),而不是使用redirectToCheckout
,在前端只使用window.location.href = sessionURL
。