如何在Magento 1.9中不使用扩展集成Google Pay支付方式
Alright, let's walk through integrating Google Pay into your Magento 1.9 store without relying on pre-built extensions. This will involve both frontend setup to render the Google Pay button and backend logic to handle payment processing.
前期准备
- First, create an account in the Google Pay Developer Console, configure your payment gateway (like Stripe, PayPal, or a custom one), and get your Merchant ID and required API keys.
- Ensure your Magento 1.9 site uses HTTPS—Google Pay requires a secure environment to work.
- Prepare your payment gateway's backend processing logic (e.g., validating payment tokens, creating orders, processing charges). Google Pay only collects payment info; actual charging is handled by your gateway.
1. Frontend Integration: Add the Google Pay Button
1.1 Load the Google Pay JavaScript Library
Add this code to the end of your theme's page/html/head.phtml file to load the Google Pay SDK:
<script async src="https://pay.google.com/gp/p/js/pay.js"></script>
1.2 Create a Container for the Google Pay Button
In your checkout page (typically checkout/onepage/payment.phtml), find the payment methods list and add a container to render the button:
<div id="google-pay-button"></div>
1.3 Initialize the Google Pay Button
Add this initialization logic to the same payment page (or a separate JS file). This example uses Stripe—adjust it for your own gateway:
document.addEventListener('DOMContentLoaded', function() { const baseRequest = { apiVersion: 2, apiVersionMinor: 0, merchantInfo: { merchantId: 'YOUR_GOOGLE_MERCHANT_ID', // Replace with your ID merchantName: 'Your Store Name' } }; const allowedPaymentMethods = [ { type: 'CARD', parameters: { allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'], allowedCardNetworks: ['AMEX', 'DISCOVER', 'MASTERCARD', 'VISA'] }, tokenizationSpecification: { type: 'PAYMENT_GATEWAY', parameters: { 'gateway': 'stripe', // Replace with your payment gateway 'stripe:publishableKey': 'YOUR_STRIPE_PUBLISHABLE_KEY', 'stripe:version': '2020-08-27' } } } ]; const paymentDataRequest = Object.assign({}, baseRequest, { allowedPaymentMethods: allowedPaymentMethods, transactionInfo: { totalPriceStatus: 'FINAL', totalPrice: '<?php echo Mage::helper('checkout')->getQuote()->getGrandTotal(); ?>', currencyCode: '<?php echo Mage::app()->getStore()->getCurrentCurrencyCode(); ?>', countryCode: 'US' // Replace with your country code } }); const paymentsClient = new google.payments.api.PaymentsClient({environment: 'TEST'}); // Use 'PRODUCTION' for live sites paymentsClient.isReadyToPay(paymentDataRequest) .then(function(response) { if (response.result) { renderGooglePayButton(); } }) .catch(function(err) { console.error('Google Pay readiness check failed:', err); }); function renderGooglePayButton() { const button = paymentsClient.createButton({ onClick: onGooglePayButtonClicked }); document.getElementById('google-pay-button').appendChild(button); } function onGooglePayButtonClicked() { paymentsClient.loadPaymentData(paymentDataRequest) .then(function(paymentData) { // Send payment token to Magento backend for processing sendPaymentToMagento(paymentData); }) .catch(function(err) { console.error('Payment data load failed:', err); }); } function sendPaymentToMagento(paymentData) { const xhr = new XMLHttpRequest(); xhr.open('POST', '/googlepay/process/payment', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { const response = JSON.parse(xhr.responseText); if (response.success) { // Redirect to checkout success page window.location.href = '/checkout/onepage/success'; } else { // Show error message alert('Payment failed: ' + response.error); } } }; xhr.send(JSON.stringify({ paymentToken: paymentData.paymentMethodData.tokenizationData.token, quoteId: '<?php echo Mage::getSingleton('checkout/session')->getQuoteId(); ?>' })); } });
Note: Adjust the tokenizationSpecification parameters to match your payment gateway's requirements.
2. Backend Integration: Create a Custom Module
2.1 Module Structure
Create these files in app/code/local/YourNamespace/GooglePay:
etc/config.xmlcontrollers/ProcessController.php
2.2 Configure config.xml
<?xml version="1.0"?> <config> <modules> <YourNamespace_GooglePay> <version>1.0.0</version> </YourNamespace_GooglePay> </modules> <frontend> <routers> <googlepay> <use>standard</use> <args> <module>YourNamespace_GooglePay</module> <frontName>googlepay</frontName> </args> </googlepay> </routers> </frontend> <global> <models> <googlepay> <class>YourNamespace_GooglePay_Model</class> </googlepay> </models> </global> </config>
2.3 Create ProcessController.php
This controller handles the payment token from the frontend and processes the payment:
<?php class YourNamespace_GooglePay_ProcessController extends Mage_Core_Controller_Front_Action { public function paymentAction() { $this->getResponse()->setHeader('Content-type', 'application/json'); $response = ['success' => false]; try { $postData = json_decode($this->getRequest()->getRawBody(), true); $quoteId = $postData['quoteId']; $paymentToken = $postData['paymentToken']; // Load the quote $quote = Mage::getModel('sales/quote')->load($quoteId); if (!$quote->getId()) { throw new Exception('Quote not found'); } // Initialize the order $service = Mage::getModel('sales/service_quote', $quote); $service->submitAll(); $order = $service->getOrder(); // Process the payment token with your gateway (example using Stripe) // \Stripe\Stripe::setApiKey('YOUR_STRIPE_SECRET_KEY'); // $charge = \Stripe\Charge::create([ // 'amount' => $order->getGrandTotal() * 100, // Amount in cents // 'currency' => $order->getOrderCurrencyCode(), // 'source' => $paymentToken, // 'description' => 'Order #' . $order->getIncrementId() // ]); // Update order status if payment succeeds $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, 'Google Pay payment successful'); $order->save(); $response['success'] = true; } catch (Exception $e) { $response['error'] = $e->getMessage(); Mage::logException($e); } $this->getResponse()->setBody(json_encode($response)); } }
2.4 Register the Module
Create app/etc/modules/YourNamespace_GooglePay.xml:
<?xml version="1.0"?> <config> <modules> <YourNamespace_GooglePay> <active>true</active> <codePool>local</codePool> </YourNamespace_GooglePay> </modules> </config>
3. Testing & Deployment
- Test first in the TEST environment using Google's test cards (e.g., 4111 1111 1111 1111, future expiry date, CVV 123).
- Once testing passes, switch the Google Pay environment from
TESTtoPRODUCTIONand ensure your Merchant ID is approved by Google. - Verify order status updates and payment gateway charge records are working correctly.
Key Notes
- Keep your Magento 1.9 installation updated to patch security vulnerabilities.
- Handle payment failures gracefully: show clear user messages and roll back order status if needed.
- Follow Google Pay's merchant policies (e.g., display refund policies, privacy terms).
内容的提问来源于stack exchange,提问作者Arijit Panigrahi

