You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PHP网站集成Square Payment Gateway无法跳转支付门户求助

Troubleshooting Square Payment Gateway Integration Issues in PHP

Let's walk through fixing your Square payment integration step by step—your issues are likely due to small configuration/script errors that are preventing the payment form from rendering and submitting correctly.

Key Issues Identified in Your Code

  1. Variable Name Typos: In sqpaymentform.js, you have a function buildForm1 that uses paymentform (lowercase "f") instead of the correct global variable name paymentForm (uppercase "F"). This breaks form initialization.
  2. Unnecessary Redundant Code: The buildForm function is unused and redundant since you're already calling paymentForm.build() directly in your index.php's DOMContentLoaded handler.
  3. Potential Unreplaced Placeholders: Ensure you've replaced APPLICATION-ID, LOCATION-ID, and ACCESS-TOKEN with your actual Square account credentials (note: Sandbox vs Production credentials are different—use Sandbox for testing).

Step-by-Step Fixes

1. Fix the sqpaymentform.js Script

Replace your current sqpaymentform.js with this cleaned-up, corrected version (make sure to fill in your actual credentials):

// Replace with your Square Sandbox/Production Application ID
var applicationId = "sb-your-app-id-here";
// Replace with your Square Location ID
var locationId = "your-location-id-here";

/*
 * Triggered when the "Pay" button is clicked
 */
function requestCardNonce(event) {
    // Prevent default form submission until we get a nonce
    event.preventDefault();
    // Request a card nonce from Square's SDK
    paymentForm.requestCardNonce();
}

// Initialize the Square Payment Form
var paymentForm = new SqPaymentForm({
    applicationId: applicationId,
    locationId: locationId,
    inputClass: 'sq-input',
    autoBuild: false,
    // Style the iframe inputs to match your site
    inputStyles: [{
        fontSize: '16px',
        fontFamily: 'Helvetica Neue',
        padding: '16px',
        color: '#373F4A',
        backgroundColor: 'transparent',
        lineHeight: '24px',
        placeholderColor: '#CCC',
        WebkitFontSmoothing: 'antialiased',
        MozOsxFontSmoothing: 'grayscale'
    }],
    applePay: false,
    masterpass: false,
    // Map form elements to Square's iframe inputs
    cardNumber: {
        elementId: 'sq-card-number',
        placeholder: 'XXXX XXXX XXXX XXXX'
    },
    cvv: {
        elementId: 'sq-cvv',
        placeholder: 'CVV'
    },
    expirationDate: {
        elementId: 'sq-expiration-date',
        placeholder: 'MM/YY'
    },
    postalCode: {
        elementId: 'sq-postal-code',
        placeholder: '12345'
    },
    callbacks: {
        createPaymentRequest: function () {
            return {
                requestShippingAddress: false,
                requestBillingInfo: true,
                currencyCode: "USD",
                countryCode: "US",
                total: {
                    label: "YOUR MERCHANT NAME",
                    amount: "100",
                    pending: false
                },
                lineItems: [{
                    label: "Subtotal",
                    amount: "100",
                    pending: false
                }]
            };
        },
        /*
         * Handle nonce generation response
         */
        cardNonceResponseReceived: function (errors, nonce, cardData) {
            if (errors) {
                // Show error messages to the user
                const errorMessage = errors.map(error => error.message).join(", ");
                document.getElementById("error").textContent = errorMessage;
                console.error("Square Nonce Errors:", errors);
                return;
            }
            // Assign nonce to hidden field and submit the form
            document.getElementById('card-nonce').value = nonce;
            document.getElementById('nonce-form').submit();
        },
        unsupportedBrowserDetected: function () {
            document.getElementById("error").textContent = "Your browser does not support this payment method.";
        },
        inputEventReceived: function (inputEvent) {
            switch (inputEvent.eventType) {
                case 'errorClassAdded':
                    document.getElementById("error").textContent = "Please fix card information errors before continuing.";
                    break;
                case 'errorClassRemoved':
                    document.getElementById("error").textContent = "";
                    break;
            }
        },
        paymentFormLoaded: function () {
            console.log("Square payment form loaded successfully!");
        }
    }
});

2. Verify Index.php Configuration

Your index.php is mostly correct, but ensure:

  • The sqpaymentform.js script loads before your DOMContentLoaded handler (which it does in your code)
  • You don't add manual <input> fields to the Square form—Square's SDK replaces the <div> elements (like sq-card-number) with secure iframes for card input. Manual inputs will break the nonce generation.

3. Validate Backend (payment-process.php)

  • Confirm you've installed the Square SDK via Composer (run composer require square/square if you haven't)—this ensures vendor/autoload.php exists.
  • Match your access_token to your environment: use a Sandbox token for testing, Production token for live payments.
  • Ensure your location_id matches the one used in sqpaymentform.js.

Testing Steps

  1. Open your browser's Developer Tools (F12) and go to the Console tab. Refresh the page—if you see errors like "applicationId invalid" or "variable not defined", fix those first.
  2. Use Square's test card details for Sandbox testing:
    • Card number: 4111 1111 1111 1111
    • Expiration date: Any future date (e.g., 12/28)
    • CVV: Any 3-digit number (e.g., 123)
    • Postal code: Any 5-digit number (e.g., 12345)
  3. Submit the form—you should see the "Payment success!" message if everything works.

内容的提问来源于stack exchange,提问作者Harish K

火山引擎 最新活动