728x90

Payment Gateway API

Payment gateways in WooCommerce are class based and can be added through traditional plugins. This guide provides an intro to gateway development.

Note: This is a Developer level doc provided as guidance. We are unable to dispense advice or review code under our Support Policy.

Types of payment gateway

Payment gateways come in several varieties:

  1. Form based – This is where the user must click a button on a form that then redirects them to the payment processor on the gateway’s own website. Example: PayPal standard, Authorize.net DPM
  2. iFrame based – This is when the gateway payment system is loaded inside an iframe on your store. Example: SagePay Form, PayPal Advanced
  3. Direct – This is when the payment fields are shown directly on the checkout page and the payment is made when ‘place order’ is pressed. Example: PayPal Pro, Authorize.net AIM
  4. Offline – No online payment is made. Example: Cheque, Bank Transfer

Form and iFrame based gateways post data offsite, meaning there are less security issues for you to think about. Direct gateways, however, require server security to be implemented (SSL certificates, etc.) and may also require a level of PCI compliance.

Creating a basic payment gateway

Note: We are unable to provide support for customizations under our Support Policy. If you are unfamiliar with code/templates and resolving potential conflicts, select a WooExpert or Developer  for assistance.

Payment gateways should be created as additional plugins that hook into WooCommerce. Inside the plugin, you need to create a class after plugins are loaded. Example:

add_action( 'plugins_loaded', 'init_your_gateway_class' );

It is also important that your gateway class extends the WooCommerce base gateway class, so you have access to important methods and the settings API:

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

You can view the WC_Payment_Gateway class in the API Docs.

As well as defining your class, you need to also tell WooCommerce (WC) that it exists. Do this by filtering woocommerce_payment_gateways:

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

Required Methods

Most methods are inherited from the WC_Payment_Gateway class, but some are required in your custom gateway.

__construct()
Within your constructor, you should define the following variables:

  • $this->id – Unique ID for your gateway, e.g., ‘your_gateway’
  • $this->icon – If you want to show an image next to the gateway’s name on the frontend, enter a URL to an image.
  • $this->has_fields – Bool. Can be set to true if you want payment fields to show on the checkout (if doing a direct integration).
  • $this->method_title – Title of the payment method shown on the admin page.
  • $this->method_description – Description for the payment method shown on the admin page.

Your constructor should also define and load settings fields:

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

We’ll cover init_form_fields() later, but this basically defines your settings that are then loaded with init_settings().

After init_settings() is called, you can get the settings and load them into variables, meaning:

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

Finally, you need to add a save hook for your settings:

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 – these are options you’ll show in admin on your gateway settings page and make use of the WC Settings API.

A basic set of settings for your gateway would consist of enabled, title and description:

$this->form_fields = array( 'enabled' => array( 'title' => __( 'Enable/Disable', 'woocommerce' ), 'type' => 'checkbox', 'label' => __( 'Enable Cheque Payment', 'woocommerce' ), 'default' => 'yes' ), 'title' => array( 'title' => __( 'Title', 'woocommerce' ), 'type' => 'text', 'description' => __( 'This controls the title which the user sees during checkout.', 'woocommerce' ), 'default' => __( 'Cheque Payment', 'woocommerce' ), 'desc_tip' => true, ), 'description' => array( 'title' => __( 'Customer Message', 'woocommerce' ), 'type' => 'textarea', 'default' => '' ) );

process_payment( $order_id )
Now for the most important part of the gateway — handling payment and processing the order. Process_payment also tells WC where to redirect the user, and this is done with a returned array.

Here is an example of a process_payment function from the Cheque gateway:

function process_payment( $order_id ) { global $woocommerce; $order = new WC_Order( $order_id ); // Mark as on-hold (we're awaiting the cheque) $order->update_status('on-hold', __( 'Awaiting cheque payment', 'woocommerce' )); // Remove cart $woocommerce->cart->empty_cart(); // Return thankyou redirect return array( 'result' => 'success', 'redirect' => $this->get_return_url( $order ) ); }

As you can see, its job is to:

  • Get and update the order being processed
  • Return success and redirect URL (in this case the thanks page)

Cheque gives the order On-Hold status since the payment cannot be verified automatically. If, however, you are building a direct gateway, then you can complete the order here instead. Rather than using update_status when an order is paid, you should use payment_complete:

$order->payment_complete();

This ensures stock reductions are made, and the status is changed to the correct value.

If payment fails, you should throw an error and return null:

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

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

Stock levels are updated via actions (woocommerce_payment_complete and in transitions between order statuses), so it’s no longer needed to manually call the methods reducing stock levels while processing the payment.

Updating Order Status and Adding Notes

Updating the order status can be done using functions in the order class. You should only do this if the order status is not processing (in which case you should use payment_complete()). An example of updating to a custom status would be:

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

The above example updates the status to On-Hold and adds a note informing the owner that it is awaiting a Cheque. You can add notes without updating the order status; this is used for adding a debug message:

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

Order Status Best Practice

  • If the order has completed but the admin needs to manually verify payment, use On-Hold
  • If the order fails and has already been created, set to Failed
  • If payment is complete, let WooCommerce handle the status and use $order->payment_complete(). WooCommerce will use either Completed or Processing status and handle stock.

Notes on Direct Gateways

If you are creating an advanced, direct gateway (i.e., one that takes payment on the actual checkout page), there are additional steps involved. First, you need to set has_fields to true in the gateway constructor:

$this->has_fields = true;

This tells the checkout to output a ‘payment_box’ containing your direct payment form that you define next.

Create a method called payment_fields() – this contains your form, most likely to have credit card details.

The next but optional method to add is validate_fields(). Return true if the form passes validation or false if it fails. You can use the wc_add_notice() function if you want to add an error and display it to the user.

Finally, you need to add payment code inside your process_payment( $order_id ) method. This takes the posted form data and attempts payment directly via the payment provider.

If payment fails, you should output an error and return nothing:

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

If payment is successful, you should set the order as paid and return the success array:

// Payment complete $order->payment_complete();// Return thank you page redirect return array( 'result' => 'success', 'redirect' => $this->get_return_url( $order ) );

Working with Payment Gateway Callbacks (such as PayPal IPN)

If you are building a gateway that makes a callback to your store to tell you about the status of an order, you need to add code to handle this inside your gateway.

The best way to add a callback and callback handler is to use WC-API hooks. An example would be as PayPal Standard does. It sets the callback/IPN URL as:

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

Then hooks in its handler to the hook:

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

WooCommerce will call your gateway and run the action when the URL is called.

For more information, see WC_API — The WooCommerce API Callback.

Hooks in Gateways

It’s important to note that adding hooks inside gateway classes may not trigger. Gateways are only loaded when needed, such as during checkout and on the settings page in admin.

You should keep hooks outside of the class or use WC-API if you need to hook into WordPress events from your class.

More Examples

For more examples of payment gateways, go to WooCommerce core gateways or WooCommerce premium gateways.

 

 

 

 

https://docs.woocommerce.com/document/payment-gateway-api/

728x90

 

A plugin is a piece of software containing a group of functions that can be added to a WordPress website.

 

Steps for creating a plugin for WooCommerce :

One of the easiest ways to create a settings page is by taking advantage of the WC_Integration class. Using the Integration class will automatically create a new settings page under WooCommerce > Settings > Integration and it will automatically save and sanitize your data for you.

1) Download and activate the latest version of WooCommerce from here: https://wordpress.org/plugins/woocommerce/

 

2) create new folder for our new plugin in wp-content/plugin/ directory.

e.g, wp-content/plugin/my-custom-plugin

 

3) WC_Integration class file. e.g, class-wc-integration-demo-integration.php.

/**
 * Integration Demo.
 *
 * @package   Woocommerce My plugin Integration
 * @category Integration
 * @author   Addweb Solution Pvt. Ltd.
 */
if ( ! class_exists( 'WC_My_plugin_Integration' ) ) :
class WC_My_plugin_Integration extends WC_Integration {
  /**
   * Init and hook in the integration.
   */
  public function __construct() {
    global $woocommerce;
    $this->id                 = 'my-plugin-integration';
    $this->method_title       = __( 'My Plugin Integration');
    $this->method_description = __( 'My Plugin Integration to show you how easy it is to extend WooCommerce.');
    // Load the settings.
    $this->init_form_fields();
    $this->init_settings();
    // Define user set variables.
    $this->custom_name          = $this->get_option( 'custom_name' );
    // Actions.
    add_action( 'woocommerce_update_options_integration_' .  $this->id, array( $this, 'process_admin_options' ) );
  }
  /**
   * Initialize integration settings form fields.
   */
  public function init_form_fields() {
    $this->form_fields = array(
      'custom_name' => array(
        'title'             => __( 'Custom Name'),
        'type'              => 'text',
        'description'       => __( 'Enter Custom Name'),
        'desc_tip'          => true,
        'default'           => '',
        'css'      => 'width:170px;',
      ),
    );
  }
}
endif; 

 

4) plugin file. e.g, woocommerce-my-custom-plugin.php

/**
 * Plugin Name: My custom plugin
 * Plugin URI: http://www.addwebsolution.com
 * Description: A plugin demonstrating how to add a new WooCommerce integration.
 * Author:  Addweb Solution Pvt. Ltd.
 * Author URI: http://www.addwebsolution.com
 * Version: 1.0
 */
if ( ! class_exists( 'WC_my_custom_plugin' ) ) :
class WC_my_custom_plugin {
  /**
  * Construct the plugin.
  */
  public function __construct() {
    add_action( 'plugins_loaded', array( $this, 'init' ) );
  }
  /**
  * Initialize the plugin.
  */
  public function init() {
    // Checks if WooCommerce is installed.
    if ( class_exists( 'WC_Integration' ) ) {
      // Include our integration class.
      include_once 'class-wc-integration-demo-integration.php';
      // Register the integration.
      add_filter( 'woocommerce_integrations', array( $this, 'add_integration' ) );
    }
  }
  /**
   * Add a new integration to WooCommerce.
   */
  public function add_integration( $integrations ) {
    $integrations[] = 'WC_My_plugin_Integration';
    return $integrations;
  }
}
$WC_my_custom_plugin = new WC_my_custom_plugin( __FILE__ );
endif;

 

Now, you can see the My custom plugin in the list of all plugins.

5) create settings link for the plugin. Add this in init() method of your plugin.

// Set the plugin slug
 define( 'MY_PLUGIN_SLUG', 'wc-settings' );

// Setting action for plugin
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'WC_my_custom_plugin_action_links' );

 

Now add the function after object creation in the plugin file.

function WC_my_custom_plugin_action_links( $links ) {

    $links[] = '<a href="'. menu_page_url( MY_PLUGIN_SLUG, false ) .'&tab=integration">Settings</a>';
    return $links;
  }

 

Now you are able to see the settings link for the plugin. It is dependent on the WooCommerce plugin activation and deactivation.

6) Click on the settings link. You are now able to save data also.

Hope this blog helps you out. Feel free to share any questions, we are ready to help always :) If you need more assistance regarding WordPress Development Service then get in touch.

 

 

 

https://addwebsolution.com/blog/creating-custom-plugin-woocommerce-using-wcintegration-class

728x90

 

다음 우편번호 API가 보안상 강화이유로 패치되었다.

완전한 패치날짜는 2021년 03월 31일 분기경이다. 

 

따라서 뒤에오는 인자에 대해서 일반적으로 잘 허용하지 않는다.

 

 

1. Cosmosfarm Customizing quotation

//wp_register_script('daum-postcode', '//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js', array('jquery'), NULL, true);
wp_enqueue_script('daum-postcode', '//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js', array('jquery'), NULL, true);

 

해당 부분에서 뒤의 인자값에 대해서 NULL 값으로 등록되는 부분으로 패치한 것을 볼 수 있다.

뒤에 인자를 추가적으로 받지 않는다. 

(예전처럼 플러그인을 만들었다거나, 추가 커스터마이징을 해서 기록을 남겨두는 의미로 뒤의 의미없는 인자를 생략하겟다는 이야기)

 

Wooshiping 에서는 WSP_VERSION 관련된 인자가 쭉 이어져서, 추적하다보면 

"class-wsp-assets.php" 에서 Version Control 을 하는 것을 볼 수 있다.

 

 

[해당 부분에서 보고 패치]

postcode.map.daum.net/guide

 

Daum 우편번호 서비스

우편번호 검색과 도로명 주소 입력 기능을 너무 간단하게 적용할 수 있는 방법. Daum 우편번호 서비스를 이용해보세요. 어느 사이트에서나 무료로 제약없이 사용 가능하답니다.

postcode.map.daum.net

 

728x90

WordPress로 운영되는 사이트나 블로그가 있는 경우 WordPress용 인스턴트 아티클 플러그인을 사용하여 쉽게 인스턴트 아티클을 만들 수 있습니다. 이 방법이 인스턴트 아티클을 만드는 가장 쉬운 방법이며 HTML 관련 경험이 필요하지 않습니다.

필수 요건

 

빠른 시작

1. 다운로드

WP용 인스턴트 아티클 플러그인을 다운로드하고 설치합니다.

2. Facebook 페이지 ID 삽입

플러그인을 설치한 다음 인스턴트 아티클 메뉴 옵션을 클릭하고 인스턴트 아티클 가입에 사용한 Facebook 페이지의 ID를 입력하세요.



인스턴트 아티클 구성 화면의 "사이트 연결" 섹션에서 페이지 ID를 가져올 수 있습니다.



3. 공유 시작

인스턴트 아티클 피드가 승인되면 게시할 수 있습니다.

다른 링크를 공유하는 것처럼 인스턴트 아티클을 배포하세요. 아티클을 포함하여 새 게시물을 구성하고 공유하면 됩니다! 인스턴트 아티클은 페이지에 자동으로 게시되지 않습니다.

 

In testing, This stage might need to push. If not, In final stage was not submited.

다음 단계

  1. 인스턴트 아티클 스타일 맞춤 설정.
  2. Facebook 블로그 팔로우. 인스턴트 아티클 뉴스 및 업데이트에 대해 알아보려면 알림에 가입하세요.
  3. 인스턴트 아티클 수익화. 자신의 직접 판매 광고 또는 Audience Network (또는 둘 다)를 사용하세요.
  4. 인터랙티브 디자인 기능 추가. 인스턴트 아티클의 고유 기능을 사용하여 독자에게 즐거움을 제공하세요.
  5. 인사이트 아티클의 분석 기능 사용. 자신 또는 타사의 트래커를 포함하는 방법을 알아보세요.
  6. 문제 해결.

+ Recent posts