如何在Flutter/React/Angular等前端框架中结合WordPress WooCommerce Mollie REST API实现支付流程
Great question—this is a super common use case when building a custom frontend for a WooCommerce store, and your initial flow is totally on the right track. Let’s break down each step with concrete details and code examples to make this work smoothly.
Overview: Your Proposed Flow (It’s Correct!)
First, let’s validate your plan—yes, this is exactly the right sequence to connect your frontend to WooCommerce and Mollie:
- Frontend user clicks "Checkout" → calls your custom WordPress REST API (
wp-json/payment/create) - Backend creates a WooCommerce order with pending status
- Backend calls Mollie’s API to generate a payment link, linking it to the WooCommerce order ID
- Backend returns the Mollie payment URL to your frontend
- Frontend redirects the user to the Mollie payment page
- After payment, Mollie notifies your backend via webhook → you update the WooCommerce order status
- Frontend confirms the payment status and updates the user interface
Step 1: Frontend – Trigger the Payment Flow
When your user clicks "Checkout", your frontend needs to send essential order details (items, user info, shipping/billing details) to your custom WordPress API. Here’s quick examples for popular frameworks:
React Example
const handleCheckout = async () => { try { const response = await fetch('https://your-wordpress-site.com/wp-json/payment/create', { method: 'POST', headers: { 'Content-Type': 'application/json', // Add WP nonce for auth if your store requires logged-in users 'X-WP-Nonce': document.querySelector('meta[name="wp_rest"]').content }, body: JSON.stringify({ items: [ { product_id: 123, quantity: 2 }, { product_id: 456, quantity: 1 } ], billing: { first_name: 'John', last_name: 'Doe', email: 'john@example.com', address_1: '123 Main St', city: 'Amsterdam', postcode: '1012 AB', country: 'NL' } }) }); const data = await response.json(); if (data.success) { // Redirect user to Mollie's payment page window.location.href = data.payment_url; } else { alert(`Checkout failed: ${data.message}`); } } catch (error) { console.error('Checkout error:', error); } };
Flutter Example
import 'package:http/http.dart' as http; import 'package:url_launcher/url_launcher.dart'; Future<void> handleCheckout() async { final url = Uri.parse('https://your-wordpress-site.com/wp-json/payment/create'); final response = await http.post( url, headers: {'Content-Type': 'application/json'}, body: jsonEncode({ 'items': [ {'product_id': 123, 'quantity': 2}, {'product_id': 456, 'quantity': 1} ], 'billing': { 'first_name': 'John', 'last_name': 'Doe', 'email': 'john@example.com', 'address_1': '123 Main St', 'city': 'Amsterdam', 'postcode': '1012 AB', 'country': 'NL' } }), ); final data = jsonDecode(response.body); if (data['success']) { await launchUrl(Uri.parse(data['payment_url'])); } else { print(`Checkout failed: ${data['message']}`); } }
Step 2: Backend – Implement the Custom REST API Endpoint
Now let’s build the WordPress side. Add this code to your theme’s functions.php file or a custom plugin:
1. Register the Payment Creation Route
add_action('rest_api_init', function () { register_rest_route( 'payment', '/create', [ 'methods' => 'POST', 'callback' => 'handle_payment_create', 'permission_callback' => function () { // Allow guest checkout: return true; // Restrict to logged-in users: return is_user_logged_in(); return true; } ] ); });
2. Implement the Payment Creation Callback
This function creates the WooCommerce order, then calls Mollie’s API to generate a payment link. First, install Mollie’s PHP SDK via Composer (composer require mollie/mollie-api-php) for easier API calls.
function handle_payment_create(WP_REST_Request $request) { $params = $request->get_json_params(); // Validate required input if (empty($params['items']) || empty($params['billing'])) { return new WP_REST_Response([ 'success' => false, 'message' => 'Missing order details' ], 400); } // 1. Create WooCommerce Order $order = wc_create_order(); if (!$order) { return new WP_REST_Response([ 'success' => false, 'message' => 'Failed to create order' ], 500); } // Add products to the order foreach ($params['items'] as $item) { $product = wc_get_product($item['product_id']); if ($product) { $order->add_product($product, $item['quantity']); } } // Set billing details $billing = $params['billing']; $order->set_billing_first_name($billing['first_name']); $order->set_billing_last_name($billing['last_name']); $order->set_billing_email($billing['email']); $order->set_billing_address_1($billing['address_1']); $order->set_billing_city($billing['city']); $order->set_billing_postcode($billing['postcode']); $order->set_billing_country($billing['country']); // Set order to pending payment status $order->update_status('pending', 'Awaiting Mollie payment confirmation'); $order->calculate_totals(); // 2. Call Mollie API to create payment require_once 'vendor/autoload.php'; $mollie = new \Mollie\Api\MollieApiClient(); $mollie->setApiKey('your_mollie_test_api_key'); // Switch to live key for production try { $payment = $mollie->payments->create([ 'amount' => [ 'value' => $order->get_total(), 'currency' => $order->get_currency() ], 'description' => 'Order #' . $order->get_id(), 'redirectUrl' => 'https://your-frontend.com/payment-confirmation?order_id=' . $order->get_id(), 'webhookUrl' => 'https://your-wordpress-site.com/wp-json/payment/webhook', 'metadata' => ['order_id' => $order->get_id()] ]); // Return payment URL to frontend return new WP_REST_Response([ 'success' => true, 'payment_url' => $payment->getCheckoutUrl(), 'order_id' => $order->get_id() ], 200); } catch (\Mollie\Api\Exceptions\ApiException $e) { // Cancel order if Mollie payment creation fails $order->update_status('cancelled', 'Mollie error: ' . $e->getMessage()); return new WP_REST_Response([ 'success' => false, 'message' => 'Failed to create payment: ' . $e->getMessage() ], 500); } }
Step 3: Handle Mollie Webhook (Confirm Payment Success)
Mollie sends a POST request to your webhook endpoint when the payment status changes (success, failed, cancelled). Let’s implement this:
1. Register the Webhook Route
add_action('rest_api_init', function () { register_rest_route( 'payment', '/webhook', [ 'methods' => 'POST', 'callback' => 'handle_mollie_webhook', 'permission_callback' => '__return_true', // Mollie needs unauthenticated access ] ); });
2. Implement the Webhook Handler
function handle_mollie_webhook(WP_REST_Request $request) { $payment_id = $request->get_param('id'); if (!$payment_id) { return new WP_REST_Response(['status' => 'error'], 400); } // Initialize Mollie client require_once 'vendor/autoload.php'; $mollie = new \Mollie\Api\MollieApiClient(); $mollie->setApiKey('your_mollie_test_api_key'); try { // Fetch payment details from Mollie to verify status $payment = $mollie->payments->get($payment_id); $order_id = $payment->metadata->order_id; $order = wc_get_order($order_id); if (!$order) { return new WP_REST_Response(['status' => 'order_not_found'], 404); } // Update order status based on Mollie's payment status switch ($payment->status) { case 'paid': $order->update_status('processing', 'Payment confirmed via Mollie'); break; case 'failed': $order->update_status('failed', 'Payment failed via Mollie'); break; case 'cancelled': $order->update_status('cancelled', 'Payment cancelled by user'); break; // Handle other statuses like 'expired' or 'pending' if needed } return new WP_REST_Response(['status' => 'success'], 200); } catch (\Mollie\Api\Exceptions\ApiException $e) { error_log('Mollie webhook error: ' . $e->getMessage()); return new WP_REST_Response(['status' => 'error'], 500); } }
Critical: Don’t forget to add this webhook URL to your Mollie Dashboard (under Developers → Webhooks) so Mollie knows where to send notifications.
Step 4: Frontend – Confirm Payment Status After Redirect
After payment, Mollie redirects users to your redirectUrl. On this page, fetch the order status from WordPress to confirm success:
React Example (Payment Confirmation Page)
useEffect(() => { const urlParams = new URLSearchParams(window.location.search); const orderId = urlParams.get('order_id'); if (orderId) { fetch(`https://your-wordpress-site.com/wp-json/payment/status?order_id=${orderId}`) .then(res => res.json()) .then(data => { if (data.status === 'processing') { setPaymentStatus('success'); } else { setPaymentStatus('failed'); } }); } }, []);
Backend: Add Order Status Endpoint
add_action('rest_api_init', function () { register_rest_route( 'payment', '/status', [ 'methods' => 'GET', 'callback' => 'handle_payment_status', 'permission_callback' => '__return_true', ] ); }); function handle_payment_status(WP_REST_Request $request) { $order_id = $request->get_param('order_id'); $order = wc_get_order($order_id); if (!$order) { return new WP_REST_Response([ 'success' => false, 'message' => 'Order not found' ], 404); } return new WP_REST_Response([ 'success' => true, 'order_id' => $order_id, 'status' => $order->get_status(), 'status_label' => wc_get_order_status_name($order->get_status()) ], 200); }
Key Tips & Troubleshooting
- Test First: Use Mollie’s test API key and test payment methods (like iDEAL test banks) before going live.
- Webhook Accessibility: Ensure your webhook URL is publicly accessible (no password protection, firewalls allow Mollie’s IPs).
- Error Handling: Add more validation in your backend (e.g., check product stock, validate address formats).
- Auth: For logged-in users, add nonce validation or JWT auth to your REST endpoints.
- Plugin Compatibility: If you’re using the Mollie for WooCommerce plugin, you can use its built-in functions instead of the SDK, but the SDK offers more flexibility.
内容的提问来源于stack exchange,提问作者Jay




