如何在WordPress网站集成Pay2All API以实现充值功能?
Got it, integrating Pay2All's API into your WordPress site to add a recharge feature is totally manageable—let’s walk through this step by step, tailored to how WordPress works:
First, lock in these basics to avoid roadblocks:
- Double-check you have all required Pay2All API credentials: API key, merchant ID, and secret key (for signing requests). Don’t skip their official docs—note down endpoints for payment initiation, status checks, and webhook requirements.
- Confirm your WordPress site runs a supported PHP version (most APIs require 7.4+). Make sure you have FTP/SSH access or can use a child theme (so changes don’t get wiped on theme updates).
We’ll use shortcodes to keep the functionality reusable and clean.
Step 2.1: Add the Recharge Form Shortcode
Drop this code into your child theme’s functions.php file or a custom plugin:
// Register recharge form shortcode add_shortcode('pay2all_recharge_form', 'pay2all_recharge_form_callback'); function pay2all_recharge_form_callback() { ob_start(); ?> <form id="recharge-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>"> <input type="hidden" name="action" value="process_pay2all_recharge"> <div style="margin: 10px 0;"> <label for="recharge_amount">Recharge Amount:</label> <input type="number" id="recharge_amount" name="recharge_amount" min="1" step="0.01" required style="margin-left: 10px;"> </div> <div style="margin: 10px 0;"> <label for="user_email">Your Email:</label> <input type="email" id="user_email" name="user_email" value="<?php echo esc_attr(get_current_user_id() ? wp_get_current_user()->user_email : ''); ?>" required style="margin-left: 30px;"> </div> <button type="submit" style="padding: 8px 16px; background: #0073aa; color: white; border: none; border-radius: 4px;">Proceed to Pay</button> </form> <?php return ob_get_clean(); }
Then create a new WordPress page (Pages → Add New) and insert [pay2all_recharge_form] into the content to display the form.
Step 2.2: Handle Payment Requests to Pay2All API
Add this code to the same functions.php or custom plugin to process form submissions and send data to Pay2All:
// Handle recharge form submission (for logged-in and guest users) add_action('admin_post_process_pay2all_recharge', 'process_pay2all_recharge'); add_action('admin_post_nopriv_process_pay2all_recharge', 'process_pay2all_recharge'); function process_pay2all_recharge() { // Validate input if (!isset($_POST['recharge_amount'], $_POST['user_email'])) { wp_redirect(add_query_arg('status', 'error', wp_get_referer())); exit; } $amount = sanitize_text_field($_POST['recharge_amount']); $email = sanitize_email($_POST['user_email']); $user_id = get_current_user_id(); $order_id = 'RECHARGE-' . $user_id . '-' . time(); // Unique order ID // Load your Pay2All credentials (store these in wp-config.php for security!) $api_key = defined('PAY2ALL_API_KEY') ? PAY2ALL_API_KEY : 'YOUR_API_KEY'; $merchant_id = defined('PAY2ALL_MERCHANT_ID') ? PAY2ALL_MERCHANT_ID : 'YOUR_MERCHANT_ID'; $secret_key = defined('PAY2ALL_SECRET_KEY') ? PAY2ALL_SECRET_KEY : 'YOUR_SECRET_KEY'; // Prepare payload (adjust fields to match Pay2All's API docs) $payload = [ 'merchant_id' => $merchant_id, 'amount' => $amount, 'currency' => 'INR', // Update to your preferred currency 'order_id' => $order_id, 'customer_email' => $email, 'customer_id' => $user_id, 'redirect_url' => home_url('/recharge-status/'), // Page to redirect post-payment 'webhook_url' => home_url('/wp-json/pay2all/v1/webhook'), // Webhook for auto-confirmation ]; // Generate signature (follow Pay2All's signing method exactly) $signature = hash('sha256', implode('|', $payload) . '|' . $secret_key); $payload['signature'] = $signature; // Send request to Pay2All's API $response = wp_remote_post('https://api.pay2all.in/payment/initiate', [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ], 'body' => json_encode($payload), 'timeout' => 30, ]); // Handle API errors if (is_wp_error($response)) { wp_redirect(add_query_arg('status', 'api_error', wp_get_referer())); exit; } $response_body = json_decode(wp_remote_retrieve_body($response), true); if ($response_body['status'] === 'success') { // Redirect user to Pay2All's payment page wp_redirect($response_body['payment_url']); exit; } else { wp_redirect(add_query_arg('status', 'payment_failed', wp_get_referer())); exit; } }
Security Note: Store your API credentials in wp-config.php instead of hardcoding them:
// Add this to wp-config.php define('PAY2ALL_API_KEY', 'your_actual_api_key'); define('PAY2ALL_MERCHANT_ID', 'your_merchant_id'); define('PAY2ALL_SECRET_KEY', 'your_secret_key');
Make a new page named "Recharge Status" and add this shortcode to display payment results:
add_shortcode('recharge_status', 'recharge_status_callback'); function recharge_status_callback() { $status = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : ''; $message = ''; switch ($status) { case 'success': $message = '<p style="color: #2ecc71; font-size: 1.1em;">Your recharge was successful! Thank you for your payment.</p>'; // Optional: Add code here to update the user's balance in WordPress break; case 'failed': $message = '<p style="color: #e74c3c; font-size: 1.1em;">Recharge failed. Please check your payment details and try again.</p>'; break; case 'error': $message = '<p style="color: #e74c3c; font-size: 1.1em;">Invalid input. Please enter a valid amount and email address.</p>'; break; case 'api_error': $message = '<p style="color: #e74c3c; font-size: 1.1em;">We couldn’t connect to the payment gateway. Please try again later.</p>'; break; default: $message = '<p>Please complete a recharge request first to see your status.</p>'; } return $message; }
Insert [recharge_status] into your Recharge Status page content.
Webhooks ensure you get payment updates even if the user closes their browser mid-payment. Add this code to create a custom REST endpoint:
// Register Pay2All webhook endpoint add_action('rest_api_init', function () { register_rest_route('pay2all/v1', '/webhook', [ 'methods' => 'POST', 'callback' => 'pay2all_webhook_handler', 'permission_callback' => '__return_true', // Verify signature instead of restricting access ]); }); function pay2all_webhook_handler(WP_REST_Request $request) { $payload = $request->get_body(); $headers = $request->get_headers(); // Verify webhook signature (match Pay2All's method) $secret_key = defined('PAY2ALL_SECRET_KEY') ? PAY2ALL_SECRET_KEY : 'YOUR_SECRET_KEY'; $received_signature = isset($headers['x-pay2all-signature'][0]) ? $headers['x-pay2all-signature'][0] : ''; $expected_signature = hash('sha256', $payload . $secret_key); if ($received_signature !== $expected_signature) { return new WP_REST_Response('Invalid signature', 403); } $data = json_decode($payload, true); if ($data['payment_status'] === 'success') { $user_id = $data['customer_id']; $amount = $data['amount']; // Update user's recharge balance (example using user meta) $current_balance = get_user_meta($user_id, 'recharge_balance', true); $new_balance = (float)$current_balance + (float)$amount; update_user_meta($user_id, 'recharge_balance', $new_balance); // Send confirmation email $user = get_user_by('id', $user_id); wp_mail($user->user_email, 'Recharge Successful', "Hi {$user->display_name},\n\nYour account has been recharged with ₹{$amount}.\nCurrent balance: ₹{$new_balance}\n\nThanks,\nYour Team" ); } return new WP_REST_Response('Webhook processed', 200); }
Don’t forget to add the webhook URL (https://your-site.com/wp-json/pay2all/v1/webhook) to your Pay2All merchant dashboard.
- Run a small test payment to verify the entire flow: form submission → API request → payment page → status update → webhook balance update.
- Ensure all user input is sanitized (we included this in the code, but double-check).
- Use WordPress’s built-in functions like
wp_remote_postinstead of raw cURL for better compatibility with hosting environments.
If custom code isn’t your vibe:
- Check if Pay2All offers an official WordPress plugin.
- Use a form builder like WPForms or Gravity Forms with a custom payment integration.
- Set up WooCommerce, create a "Recharge" product, and integrate Pay2All as a custom payment gateway.
内容的提问来源于stack exchange,提问作者swapnil agrawal




