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
- Variable Name Typos: In
sqpaymentform.js, you have a functionbuildForm1that usespaymentform(lowercase "f") instead of the correct global variable namepaymentForm(uppercase "F"). This breaks form initialization. - Unnecessary Redundant Code: The
buildFormfunction is unused and redundant since you're already callingpaymentForm.build()directly in your index.php's DOMContentLoaded handler. - Potential Unreplaced Placeholders: Ensure you've replaced
APPLICATION-ID,LOCATION-ID, andACCESS-TOKENwith 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.jsscript 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 (likesq-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/squareif you haven't)—this ensuresvendor/autoload.phpexists. - Match your
access_tokento your environment: use a Sandbox token for testing, Production token for live payments. - Ensure your
location_idmatches the one used insqpaymentform.js.
Testing Steps
- 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.
- 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)
- Card number:
- Submit the form—you should see the "Payment success!" message if everything works.
内容的提问来源于stack exchange,提问作者Harish K




