Integrating Stripe with WooCommerce in a WordPress Multisite environment can enhance your eCommerce capabilities, providing a seamless payment gateway across multiple stores. This article will guide you through creating a custom plugin to achieve this integration, complete with code samples.
Prerequisites
- Basic understanding of WordPress development.
- Familiarity with WooCommerce.
- Knowledge of PHP and JavaScript.
- Access to a WordPress Multisite network with WooCommerce installed.
- A Stripe account with API keys.
Step 1: Setting Up Your Plugin
First, create a folder for your plugin in the wp-content/plugins
directory of your WordPress installation. Name it woocommerce-multisite-stripe
. Inside this folder, create a file named woocommerce-multisite-stripe.php
.
php<?php
/*
Plugin Name: WooCommerce Multisite Stripe Integration
Description: Integrates Stripe payment gateway with WooCommerce in a WordPress Multisite environment.
Version: 1.0
Author: Your Name
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly.
}
// Include the main class file
require_once plugin_dir_path(__FILE__) . 'includes/class-wc-multisite-stripe.php';
// Initialize the plugin
add_action('plugins_loaded', 'init_wc_multisite_stripe');
function init_wc_multisite_stripe() {
if (class_exists('WC_Payment_Gateway')) {
new WC_Multisite_Stripe();
}
}
Step 2: Creating the Main Plugin Class
Create a new directory inside your plugin folder named includes
. Inside this folder, create a file named class-wc-multisite-stripe.php
.
php<?php
if (!defined('ABSPATH')) {
exit;
}
class WC_Multisite_Stripe extends WC_Payment_Gateway {
public function __construct() {
$this->id = 'multisite_stripe';
$this->method_title = __('Stripe Multisite', 'woocommerce');
$this->method_description = __('Stripe Payment Gateway for WooCommerce Multisite.', 'woocommerce');
$this->has_fields = false;
// Load the settings
$this->init_form_fields();
$this->init_settings();
// Define user settings variables
$this->title = $this->get_option('title');
$this->description = $this->get_option('description');
$this->enabled = $this->get_option('enabled');
$this->testmode = 'yes' === $this->get_option('testmode');
$this->publishable_key = $this->get_option('publishable_key');
$this->secret_key = $this->get_option('secret_key');
// Actions
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
// Payment listener/API hook
add_action('woocommerce_api_wc_' . $this->id, array($this, 'check_response'));
}
// Initialize Gateway Settings Form Fields
public function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'checkbox',
'label' => __('Enable Stripe Payment', 'woocommerce'),
'default' => 'yes'
),
'title' => array(
'title' => __('Title', 'woocommerce'),
'type' => 'text',
'description' => __('Title to be displayed on the checkout page.', 'woocommerce'),
'default' => __('Stripe', 'woocommerce'),
'desc_tip' => true,
),
'description' => array(
'title' => __('Description', 'woocommerce'),
'type' => 'textarea',
'description' => __('Description to be displayed on the checkout page.', 'woocommerce'),
'default' => __('Pay securely using your credit card via Stripe.', 'woocommerce'),
'desc_tip' => true,
),
'testmode' => array(
'title' => __('Test Mode', 'woocommerce'),
'type' => 'checkbox',
'label' => __('Enable Test Mode', 'woocommerce'),
'default' => 'yes',
'description' => __('Test mode uses Stripe Sandbox API keys.', 'woocommerce'),
'desc_tip' => true,
),
'publishable_key' => array(
'title' => __('Publishable Key', 'woocommerce'),
'type' => 'text',
'description' => __('Your Stripe publishable key.', 'woocommerce'),
'default' => '',
'desc_tip' => true,
),
'secret_key' => array(
'title' => __('Secret Key', 'woocommerce'),
'type' => 'password',
'description' => __('Your Stripe secret key.', 'woocommerce'),
'default' => '',
'desc_tip' => true,
),
);
}
// Process the payment and return the result
public function process_payment($order_id) {
global $woocommerce;
$order = wc_get_order($order_id);
// Include the Stripe PHP bindings library
require_once plugin_dir_path(__FILE__) . 'lib/stripe-php/init.php';
// Set the API key
\Stripe\Stripe::setApiKey($this->secret_key);
try {
$charge = \Stripe\Charge::create(array(
'amount' => $order->get_total() * 100,
'currency' => strtolower(get_woocommerce_currency()),
'source' => $_POST['stripeToken'],
'description' => sprintf(__('Order #%s', 'woocommerce'), $order->get_order_number())
));
if ($charge->status == 'succeeded') {
$order->payment_complete();
$order->add_order_note(__('Stripe payment completed.', 'woocommerce'));
$woocommerce->cart->empty_cart();
return array(
'result' => 'success',
'redirect' => $this->get_return_url($order)
);
} else {
wc_add_notice(__('Payment error:', 'woocommerce') . $charge->failure_message, 'error');
return;
}
} catch (Exception $e) {
wc_add_notice(__('Payment error:', 'woocommerce') . $e->getMessage(), 'error');
return;
}
}
// Receipt page
public function receipt_page($order) {
echo '<p>' . __('Thank you for your order, please click the button below to pay with Stripe.', 'woocommerce') . '</p>';
echo '<form id="stripe_payment_form" method="post">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="' . $this->publishable_key . '"
data-amount="' . (wc_get_order($order->get_id())->get_total() * 100) . '"
data-name="' . get_bloginfo('name') . '"
data-description="' . sprintf(__('Order #%s', 'woocommerce'), $order->get_order_number()) . '"
data-email="' . $order->get_billing_email() . '"
data-currency="' . strtolower(get_woocommerce_currency()) . '"
data-locale="auto">
</script>
</form>';
}
// Check response
public function check_response() {
// Handle the response from Stripe
}
}
Step 3: Enabling the Payment Gateway
Now, to make this new payment gateway available in WooCommerce, add the following code to the init_wc_multisite_stripe
function in woocommerce-multisite-stripe.php
:
phpfunction init_wc_multisite_stripe() {
if (class_exists('WC_Payment_Gateway')) {
new WC_Multisite_Stripe();
add_filter('woocommerce_payment_gateways', 'add_wc_multisite_stripe_gateway');
}
}
function add_wc_multisite_stripe_gateway($methods) {
$methods[] = 'WC_Multisite_Stripe';
return $methods;
}
Step 4: Testing the Plugin
- Activate the plugin from the WordPress admin panel for the sites where you want to use Stripe.
- Navigate to WooCommerce > Settings > Payments and enable the Stripe Multisite gateway.
- Configure your Stripe API keys in the plugin settings.
- Test the checkout process using a test credit card number from Stripe's documentation.
Creating a custom WooCommerce payment gateway for a WordPress Multisite network with Stripe integration requires a good understanding of both WooCommerce and Stripe APIs. This guide provides a solid foundation for building a custom plugin to manage Stripe payments across multiple stores. By following these steps and utilizing the code samples provided, you can customize the payment process to fit your specific needs.
For more advanced features, consider exploring Stripe's extensive API documentation and WooCommerce's developer resources.
Here are some additional code samples and explanations to help you understand and expand upon the custom WooCommerce Multisite Stripe integration plugin.
Step 5: Adding Webhook Support
To enhance the functionality of your Stripe integration, you can add webhook support. This allows your WooCommerce store to receive updates from Stripe regarding payment events.
Webhook Handler
Create a new file named class-wc-multisite-stripe-webhook-handler.php
in the includes
directory:
php<?php
if (!defined('ABSPATH')) {
exit;
}
class WC_Multisite_Stripe_Webhook_Handler {
public function __construct() {
add_action('woocommerce_api_wc_multisite_stripe', array($this, 'handle_webhook'));
}
public function handle_webhook() {
$body = @file_get_contents('php://input');
$event = json_decode($body);
if (json_last_error() !== JSON_ERROR_NONE) {
status_header(400);
exit;
}
if (!isset($event->type)) {
status_header(400);
exit;
}
switch ($event->type) {
case 'charge.succeeded':
$this->handle_charge_succeeded($event);
break;
case 'charge.failed':
$this->handle_charge_failed($event);
break;
// Add other event types as needed
default:
status_header(200);
exit;
}
}
protected function handle_charge_succeeded($event) {
$charge = $event->data->object;
$order_id = $charge->metadata->order_id;
$order = wc_get_order($order_id);
if ($order && $order->get_payment_method() === 'multisite_stripe') {
$order->payment_complete();
$order->add_order_note(__('Stripe payment completed via webhook.', 'woocommerce'));
}
status_header(200);
exit;
}
protected function handle_charge_failed($event) {
$charge = $event->data->object;
$order_id = $charge->metadata->order_id;
$order = wc_get_order($order_id);
if ($order && $order->get_payment_method() === 'multisite_stripe') {
$order->update_status('failed', __('Stripe payment failed via webhook.', 'woocommerce'));
}
status_header(200);
exit;
}
}
Register the Webhook Handler
Include and initialize the webhook handler in the main plugin file woocommerce-multisite-stripe.php
:
phprequire_once plugin_dir_path(__FILE__) . 'includes/class-wc-multisite-stripe-webhook-handler.php';
function init_wc_multisite_stripe() {
if (class_exists('WC_Payment_Gateway')) {
new WC_Multisite_Stripe();
new WC_Multisite_Stripe_Webhook_Handler();
add_filter('woocommerce_payment_gateways', 'add_wc_multisite_stripe_gateway');
}
}
Adding Metadata to Charges
Modify the process_payment
method in class-wc-multisite-stripe.php
to include order metadata:
php$charge = \Stripe\Charge::create(array(
'amount' => $order->get_total() * 100,
'currency' => strtolower(get_woocommerce_currency()),
'source' => $_POST['stripeToken'],
'description' => sprintf(__('Order #%s', 'woocommerce'), $order->get_order_number()),
'metadata' => array(
'order_id' => $order_id
)
));
Step 6: Adding Admin Notices for Configuration Issues
To alert the site administrator of potential configuration issues, you can add admin notices.
Admin Notice Class
Create a new file named class-wc-multisite-stripe-admin-notices.php
in the includes
directory:
php<?php
if (!defined('ABSPATH')) {
exit;
}
class WC_Multisite_Stripe_Admin_Notices {
public function __construct() {
add_action('admin_notices', array($this, 'check_stripe_configuration'));
}
public function check_stripe_configuration() {
if (!is_plugin_active('woocommerce/woocommerce.php')) {
echo '<div class="notice notice-error"><p>' . __('WooCommerce must be installed and activated to use the Stripe Multisite plugin.', 'woocommerce') . '</p></div>';
}
if (!get_option('woocommerce_multisite_stripe_settings')) {
echo '<div class="notice notice-error"><p>' . __('Stripe Multisite plugin is not configured. Please go to WooCommerce settings and configure the plugin.', 'woocommerce') . '</p></div>';
}
}
}
Register the Admin Notice Class
Include and initialize the admin notice class in the main plugin file woocommerce-multisite-stripe.php
:
phprequire_once plugin_dir_path(__FILE__) . 'includes/class-wc-multisite-stripe-admin-notices.php';
function init_wc_multisite_stripe() {
if (class_exists('WC_Payment_Gateway')) {
new WC_Multisite_Stripe();
new WC_Multisite_Stripe_Webhook_Handler();
new WC_Multisite_Stripe_Admin_Notices();
add_filter('woocommerce_payment_gateways', 'add_wc_multisite_stripe_gateway');
}
}
Step 7: Adding Custom Payment Fields
To enhance the user experience, you can add custom payment fields such as billing phone number or custom notes.
Custom Payment Fields
Add the following methods to the WC_Multisite_Stripe
class in class-wc-multisite-stripe.php
:
phppublic function payment_fields() {
parent::payment_fields();
echo '<div id="custom_payment_fields">';
echo '<p class="form-row form-row-wide">
<label for="billing_phone">' . __('Billing Phone', 'woocommerce') . ' <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_phone" id="billing_phone" required />
</p>';
echo '<p class="form-row form-row-wide">
<label for="custom_note">' . __('Custom Note', 'woocommerce') . '</label>
<textarea class="input-text" name="custom_note" id="custom_note"></textarea>
</p>';
echo '</div>';
}
public function validate_fields() {
if (empty($_POST['billing_phone'])) {
wc_add_notice(__('Billing phone is a required field.', 'woocommerce'), 'error');
return false;
}
return true;
}
public function process_payment($order_id) {
if (!$this->validate_fields()) {
return;
}
$order = wc_get_order($order_id);
$order->set_billing_phone(sanitize_text_field($_POST['billing_phone']));
$order->update_meta_data('_custom_note', sanitize_textarea_field($_POST['custom_note']));
$order->save();
// Proceed with Stripe payment processing
}
Display Custom Fields in Admin Order Details
Add the following code to class-wc-multisite-stripe.php
to display custom fields in the admin order details:
phpadd_action('woocommerce_admin_order_data_after_billing_address', 'display_custom_fields_in_admin_order_meta', 10, 1);
function display_custom_fields_in_admin_order_meta($order) {
echo '<p><strong>' . __('Billing Phone') . ':</strong> ' . get_post_meta($order->get_id(), '_billing_phone', true) . '</p>';
echo '<p><strong>' . __('Custom Note') . ':</strong> ' . get_post_meta($order->get_id(), '_custom_note', true) . '</p>';
}
Conclusion
By following these additional steps and using the provided code samples, you can further enhance your custom WooCommerce Multisite Stripe integration plugin. These enhancements include webhook support, admin notices, and custom payment fields, which together create a more robust and user-friendly payment gateway solution.
Feel free to expand and customize these samples to fit the specific needs of your WooCommerce Multisite environment. For more advanced customization, always refer to the official Stripe API documentation and WooCommerce developer documentation.