在 Squarespace 上实现 Stripe 时出现未知的 HTML/JS 错误

问题描述 投票:0回答:1

从源“https://js.stripe.com”获取“https://merchant-ui-api.stripe.com/elements/wallet-config”的访问已被 CORS 策略阻止:无“访问-” Control-Allow-Origin'标头存在于所请求的资源上。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

我一直在尝试使用代码块在正方形空间上实现简单的条纹形式,但出现此错误。知道如何排除故障吗? ChatGPT 没有帮助。

这是我的 HTML

<!-- Include the Stripe.js library -->
<script src="https://js.stripe.com/v3/"></script>

<div class="course-details-container">
  <h1>10-Week Python Course for Minorities</h1>
  <p>Join our comprehensive 10-week Python course designed specifically for minorities. Learn the fundamentals of Python programming and gain the skills needed to succeed in the tech industry.</p>
  
  <h2>Course Details</h2>
  <ul>
    <li><strong>Duration:</strong> 10 weeks</li>
    <li><strong>Start Date:</strong> July 22nd-October 12th 2024</li>
    <li><strong>Format:</strong> Live and Virtual</li>
    <li><strong>Instructor:</strong> Babatunde David Ogundipe</li>
  </ul>
  
  <h2>What You'll Learn</h2>
  <ul>
    <li>Python basics: syntax, variables, and data types</li>
    <li>Control structures: loops and conditionals</li>
    <li>Functions and modules</li>
    <li>Working with libraries and APIs</li>
    <li>Object-oriented programming</li>
    <li>Data manipulation and analysis</li>
    <li>Automation</li>
    <li>Building projects and portfolios</li>
  </ul>
  
  <h2>Enroll Now</h2>
  <p>To secure your spot in the course, please fill out the form below:</p>
  
  <form id="payment-form">
    <label for="amount">Select Amount:</label>
    <select id="amount" name="amount" required>
      <option value="200">Donation - $2</option>
      <option value="18000">Tuition - $180</option>
      <option value="50000">Full Tuition - $500</option>
    </select>
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    <div>
      <label for="card-element">Credit or debit card</label>
      <div id="card-element"></div>
      <div id="card-errors" role="alert"></div>
    </div>
    <button id="submit">Submit Payment</button>
  </form>
</div>

<!-- Custom CSS for styling -->
<style>
  .course-details-container {
    font-family: Arial, sans-serif;
    max-width: 800px;
    margin: auto;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  .course-details-container h1 {
    color: #333;
    font-size: 24px; /* Reduced font size */
  }
  .course-details-container h2 {
    color: #333;
    font-size: 20px; /* Reduced font size */
  }
  .course-details-container p, .course-details-container ul, .course-details-container li {
    font-size: 14px; /* Reduced font size */
  }
  .course-details-container ul {
    list-style-type: disc;
    padding-left: 20px;
  }
  #payment-form {
    margin-top: 20px;
  }
  #payment-form label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px; /* Reduced font size */
  }
  #payment-form input, #payment-form select, #payment-form textarea {
    width: 100%;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 14px; /* Reduced font size */
  }
  #payment-form button {
    padding: 10px 20px;
    background-color: #28a745;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px; /* Reduced font size */
  }
  #payment-form button:hover {
    background-color: #218838;
  }
  #card-element {
    border: 1px solid #ccc;
    padding: 10px;
    border-radius: 4px;
    font-size: 14px; /* Reduced font size */
  }
  #card-errors {
    color: #fa755a;
    margin-top: 10px;
  }
</style>

<!-- Your custom JavaScript for Stripe Elements integration -->
<script>
  document.addEventListener("DOMContentLoaded", function() {
    var stripe = Stripe('pk_live_51PSrG8RxlYkqL9qpR8tgNraE3e55q1oWJ37M2HQKqIQ5T48J8P9uj6WLETmQGrQs6xaKpSTOYcrsCXy6jcFdxMNh000XhnUFzj');  // Replace with your Stripe publishable key
    var elements = stripe.elements();
    
    var style = {
      base: {
        color: '#32325d',
        lineHeight: '24px',
        fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
        fontSmoothing: 'antialiased',
        fontSize: '16px',
        '::placeholder': {
          color: '#aab7c4'
        }
      },
      invalid: {
        color: '#fa755a',
        iconColor: '#fa755a'
      }
    };

    var card = elements.create('card', {style: style});
    card.mount('#card-element');

    card.on('change', function(event) {
      var displayError = document.getElementById('card-errors');
      if (event.error) {
        displayError.textContent = event.error.message;
      } else {
        displayError.textContent = '';
      }
    });

    var form = document.getElementById('payment-form');
    form.addEventListener('submit', function(event) {
      event.preventDefault();

      // Get selected amount
      var amountSelect = document.getElementById('amount');
      var amount = amountSelect.options[amountSelect.selectedIndex].value;

      fetch('https://your-heroku-app.herokuapp.com/create-payment-intent', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          amount: parseInt(amount)  // Amount in cents
        }),
      }).then(function(result) {
        return result.json();
      }).then(function(data) {
        if (data.error) {
          var errorElement = document.getElementById('card-errors');
          errorElement.textContent = data.error;
        } else {
          stripe.confirmCardPayment(data.clientSecret, {
            payment_method: {
              card: card,
              billing_details: {
                name: document.getElementById('name').value,
                email: document.getElementById('email').value
              }
            }
          }).then(function(result) {
            if (result.error) {
              var errorElement = document.getElementById('card-errors');
              errorElement.textContent = result.error.message;
            } else {
              // The payment succeeded
              alert('Payment pre-authorized! We will contact you soon.');
            }
          });
        }
      });
    });
  });
</script>

这是我用于创建付款的后端Python代码

from flask import Flask, request, jsonify
import stripe
from config import api_key
from flask_cors import CORS


stripe.api_key = api_key

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes


@app.route('/create-payment-intent', methods=['POST'])
def create_payment_intent():
    """
    Endpoint to create a payment intent. This pre-authorizes a payment
    but does not capture the funds until later.
    """
    try:
        data = request.json  # Get the JSON data from the request body
        if not data:
            return jsonify(error="No JSON payload provided"), 400
        
        # Extract amount from the request data
        amount = data.get('amount')
        if not amount:
            return jsonify(error="Amount is required"), 400

        # Validate amount (only accept $180 or $500)
        if amount not in [200,18000, 50000]:  # Amounts in cents
            return jsonify(error="Invalid amount"), 400

        # Create a PaymentIntent with manual capture method
        intent = stripe.PaymentIntent.create(
            amount=amount,  # amount in cents
            currency='usd',
            payment_method_types=['card'],
            capture_method='manual',  # Set to manual to pre-authorize the payment
        )
        # Return the client secret to the client
        return jsonify({'clientSecret': intent['client_secret'], 'paymentIntentId': intent['id']})
    except stripe.error.StripeError as e:
        # Handle Stripe-specific errors
        body = e.json_body
        err = body.get('error', {})
        return jsonify(error=err.get('message')), 403
    except Exception as e:
        # Handle general errors
        return jsonify(error=str(e)), 500
javascript html stripe-payments
1个回答
0
投票

您可能想询问 squarespace 他们是否在您的页面上添加了任何默认 CSP,并相应地包含 Stripe 的 directives

© www.soinside.com 2019 - 2024. All rights reserved.