How to create a custom payment gateway using the WooCommerce Payment Gateway API

The WooCommerce payment gateway API is a class-based interface that we can use to develop a custom interface for WooCommercepayment gatewayWordPress plug-in, in this article, we will introduce to you how to add a payment gateway to WooCommerce using the payment gateway API.

Types of WooCommerce payment gateways

WooCommerce has 4 typespayment gateway

  1. form based– In this method, the user must click the submit button in the form and then be redirected to the third-party payment gateway’s website to process the payment. Such as PayPal standard interface, Authorize.net DPM, Alipay.
  2. Based on iFrame– This method loads the gateway payment system within an iframe,like: SagePay form, PayPal advanced interface.
  3. Pay directly– If you use this payment method, when you click ‘Place Order’ on the checkout page, the payment has been successful. Such as: PayPal Pro, Authorize.net AIM
  4. Offline payment– No online processing.like: Check, Bank Transfer

Form-based and iframe-based payment methods need to send post data to the corresponding third-party payment gateway site. There are not many security issues to consider. Direct payment needs to implement server-side encryption (SSL certification) and may also need to be compatible.PCI standard

Create a basic payment gateway

The payment gateway needs to be mounted into WooCommerce as an additional plug-in. In the plug-in, we need to create a class to implement the payment gateway function after the plug-in is loaded. Here’s an example:

add_action( 'plugins_loaded', 'init_your_gateway_class' );

It is also very important that the additional gateway class we create must inherit the WooCommerce payment gateway base class so that we can access the important methods and settings API in the payment gateway.

function init_your_gateway_class() {
  class WC_Gateway_Your_Gateway extends WC_Payment_Gateway {}
}

Can be viewed via APIWC_Payment_GatewayIntroduction and documentation.

After defining the custom payment gateway class, we need to let WooCommerce (WC) know the existence of the custom payment gateway. Just register it through woocommerce_payment_gateways, as follows:

function add_your_gateway_class( $methods ) {
	$methods[] = 'WC_Gateway_Your_Gateway'; 
	return $methods;
}

add_filter( 'woocommerce_payment_gateways', 'add_your_gateway_class' );

required method

Most methods are inherited directly from the WC_Payment_Gateway class, and a few methods need to be customized in the gateway.

__construct()
In the constructor, we need to define variables:

  • $this->id– The unique ID of the payment gateway, such as ‘your_gateway’.
  • $this->icon– If you need to display an icon after the payment gateway name on the frontend, define the image URLI here.
  • $this->has_fields– Boolean value, set to true if you want payments to be custom displayed on the checkout page, (used when creating a direct payment gateway).
  • $this->method_title– The name of the payment gateway shown in the payment method list on the admin page.
  • $this->method_description– Payment gateway description displayed in the payment methods list on the admin page.

The constructor should also define and load settings fields:

$this->init_form_fields();
$this->init_settings();

We will explain in detail belowinit_form_fields(), define the settings here first, and then passinit_settings()Just load it.

init_settings()After the call, we can get the setting value and load it into a variable, as follows:

$this->title = $this->get_option( 'title' );

Finally, we need to add a method to the save settings hook:

add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );

init_form_fields()
Use this method to set$this->form_fields– There will be some options added to the payment gateway’s settings page viaWC Settings APIAdd to.

At the very least, we should add 3 basic settings fields – enabled, title, and description:

$this->form_fields = array(
	'enabled' => array(
		'title' => __( '启用/禁用', 'woocommerce' ),
		'type' => 'checkbox',
		'label' => __( '启用该支付方法', 'woocommerce' ),
		'default' => 'yes'
	),
	'title' => array(
		'title' => __( '标图', 'woocommerce' ),
		'type' => 'text',
		'description' => __( '显示为结账页面的支付方法标题', 'woocommerce' ),
		'default' => __( '支付宝支付', 'woocommerce' ),
		'desc_tip'      => true,
	),
	'description' => array(
		'title' => __( '自定义支付网关描述信息', 'woocommerce' ),
		'type' => 'textarea',
		'default' => ''
	)
);

process_payment( $order_id )
This method is the most important part of the custom payment gateway. It is responsible for payment and order processing. Process_payment also tells WC what page to redirect the user to. The above processing is implemented through an array returned.

Here is an example process_payment function extracted from the Cheque payment gateway:

function process_payment( $order_id ) {
	global $woocommerce;
	$order = new WC_Order( $order_id );

	// 更新订单状态为等待中 (等待第三方支付网关返回)
	$order->update_status('on-hold', __( 'Awaiting cheque payment', 'woocommerce' ));

	// 减少库存
	$order->reduce_order_stock();

	// 清空购物车
	$woocommerce->cart->empty_cart();

	// 返回感谢购物页面跳转
	return array(
		'result' => 'success',
		'redirect' => $this->get_return_url( $order )
	);
}

As seen above, the above method completes the following tasks:

  • Get and update the order status to waiting or payment successful
  • Reduce inventory and clear shopping cart
  • Returns success information and jumps to the specified URL (in this example, the purchase page)

Check cannot automatically confirm the payment status, so specify the order status as “Pending”. If the payment gateway we create can automatically determine the order status, we can complete the order directly.

$order->payment_complete();

This method ensures that the inventory is reduced accordingly and the order status is modified to the correct value.

If the payment fails, we should report an error and return null:

wc_add_notice( __('Payment error:', 'woothemes') . $error_message, 'error' );
return;

WooCommerce will catch this error and display it on the checkout page.

Update order status and add order notes

To update the order status, you can use the methods in the order class. We should only update the order status when the order is not processed. If the order is processed successfully, we should use the payment_complete() method to complete the order. Here’s an example of updating order status:

$order = new WC_Order( $order_id );
$order->update_status('on-hold', __('Awaiting cheque payment', 'woothemes'));

The above strength code updates the order status to “Waiting” and adds an order note to notify the administrator that it is waiting for confirmation from the Cheque gateway. We can use the add_order_note() method to directly add the order note without updating the order status to facilitate debugging the payment gateway.

$order->add_order_note( __('IPN payment completed', 'woothemes') );

Order Status Best Practices

  • If the order is completed but requires manual confirmation by the administrator, use“Waiting”state.
  • If the order payment fails, set to“invalid”
  • If payment has been completed, use$order->payment_complete()Method to let WooCommerce set the order status and note information WooCommerce will useCompletedorProcessingstatus and handle inventory.

Direct payment gateway considerations

If we are creating an advanced, direct payment gateway (making payments directly on the payment page), there are a few additional steps that need to be completed:

$this->has_fields = true;

This variable tells the payment page to output a ‘payment_box’ container that displays the payment gateway information we defined.

Create a file namedpayment_fields()method – This method contains a form information, similar to a credit card payment style.

The next optional step is to add avalidate_fields(), if the form passes validation, returns true, otherwise returns false. If you need to display an error message, you can usewc_add_notice()function.

Finally, we need toprocess_payment( $order_id )Add payment code to the method. This code obtains the data submitted by the form and pays through a third-party payment gateway.

If the payment fails, we should output an error message and return no information.

wc_add_notice( __('Payment error:', 'woothemes') . $error_message, 'error' );
return;

If the payment is successful, we should set the order as “paid” and return an array of success information.

// 支付完成
$order->payment_complete();
// 返回成功信息,并跳转到感谢后买页面。
return array(
	'result' => 'success',
	'redirect' => $this->get_return_url( $order )
);

Payment gateway callback

If we are developing a gateway that supports the use of callbacks to pass back order status, we need to add code in the gateway to handle the callbacks. The best way to add callbacks and callback methods is to usewoocommerce_api_(action) Action hook, here is an example of PayPal’s standard approach, setting the callback/IPN URL to:

str_replace( 'https:', 'http:', add_query_arg( 'wc-api', 'WC_Gateway_Paypal', home_url( '/' ) ) );

Then mount his own processing method on the hook:

add_action( 'woocommerce_api_wc_gateway_paypal', array( $this, 'check_ipn_response' ) );

When the payment website returns information to our defined payment callback URL, WooCommerce will call our custom payment gateway and perform the corresponding operations.

For more information, seeWC_API documentation

Payment Gateway Hooks

It is important to note that adding functionality to the payment gateway class may not be triggered. The payment gateway will only be loaded when needed, such as on the payment page or backend management page. If we need to mount WordPress events into a class, we should mount it outside the class or use WC-API.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *