Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate installment payment with WC blocks #455

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions assets/css/omise-css.css
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ fieldset.card-exists,
* 2.3). Form, bank list components
*/
ul.omise-banks-list {
list-style-type: none;
margin: 0;
}

Expand Down Expand Up @@ -284,6 +285,7 @@ ul.omise-banks-list {
/** Media Quries **/
@media all and (min-width: 375px) {
ul.omise-banks-list {
list-style-type: none;
margin: 0 0 0 1.75em;
}

Expand All @@ -303,6 +305,7 @@ ul.omise-banks-list {

@media all and (min-width: 768px) {
ul.omise-banks-list {
list-style-type: none;
margin: 0;
}

Expand All @@ -319,6 +322,7 @@ ul.omise-banks-list {

@media all and (min-width: 1024px) {
ul.omise-banks-list {
list-style-type: none;
margin: 0 0 0 1.75em;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<?php return array('dependencies' => array('react', 'wc-blocks-registry', 'wc-settings', 'wp-element', 'wp-html-entities', 'wp-i18n'), 'version' => '9dc70441197f527b0184197ad3d95e93');
1 change: 1 addition & 0 deletions includes/blocks/assets/js/build/omise_installment.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

120 changes: 120 additions & 0 deletions includes/blocks/assets/js/omise-installment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import {useEffect, useState, useRef} from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { decodeEntities } from '@wordpress/html-entities';
import { registerPaymentMethod } from '@woocommerce/blocks-registry';
import { getSetting } from '@woocommerce/settings';

const settings = getSetting( 'omise_installment_data', {} )
const label = decodeEntities( settings.title ) || 'No title set'
const Label = ( props ) => {
const { PaymentMethodLabel } = props.components
return <PaymentMethodLabel text={ label } />
}

const InstallmentPaymentMethod = (props) => {
const {eventRegistration, emitResponse} = props;
const {onPaymentSetup} = eventRegistration;
const description = decodeEntities( settings.description || '' )
const { installment_backends, is_zero_interest } = settings.data;
const noPaymentMethods = __( 'Purchase Amount is lower than the monthly minimum payment amount.', 'omise' );
const installmentRef = useRef(null);
const termRef = useRef(null);

const onInstallmentSelected = (e) => {
installmentRef.current = e.target.value
termRef.current = null
}

const onTermsSelected = (e) => {
termRef.current = e.target.value
}

useEffect(() => {
const unsubscribe = onPaymentSetup(async () => {
if (!installmentRef.current || !termRef.current) {
return {type: emitResponse.responseTypes.ERROR, message: 'Select a bank and term'}
}
try {
return {
type: emitResponse.responseTypes.SUCCESS,
meta: {
paymentMethodData: {
"source": installmentRef.current,
[`${installmentRef.current}_installment_terms`]: termRef.current,
}
}
};
} catch (error) {
return {type: emitResponse.responseTypes.ERROR, message: error.message}
}
});
return () => unsubscribe();
}, [ onPaymentSetup ]);

return (<>
{description && <p>{description}</p>}
{
installment_backends.length == 0
? <p>{noPaymentMethods}</p>
: (
<fieldset id="omise-form-installment">
<ul className="omise-banks-list">
{
installment_backends.map((backend, i) => (
<li key={backend['_id'] + i} className="item">
<input id={backend['_id']} type="radio" name="source[type]" value={backend['_id']} onChange={onInstallmentSelected} />
<label htmlFor={backend['_id']}>
<div className={`bank-logo ${backend['provider_code']}`}></div>
<div className="bank-label">
<span className="title">{backend['provider_name']}</span><br/>
<select
id={`${backend['_id']}_installment_terms`}
name={`${backend['_id']}_installment_terms`}
className="installment-term-select-box"
onChange={onTermsSelected}
>
<option>Select term</option>
{
backend['available_plans'].map((installment_plan, i) => (
<option
key={`${installment_plan['term_length']}_${installment_plan['monthly_amount']}_${i}`}
value={installment_plan['term_length']}
>
{__(`${installment_plan['term_length']} months`, 'omise')}
<>&nbsp;</>
({__(`${installment_plan['monthly_amount']} / months`, 'omise')})
</option>
))
}
</select>
{
is_zero_interest && <>
<br />
<span className="omise-installment-interest-rate">
{__( `( interest ${backend.interest_rate} )`, 'omise' )}
</span>
</>
}
</div>
</label>
</li>
))
}
</ul>
</fieldset>
)
}
</>)
}

registerPaymentMethod( {
name: settings.name,
label: <Label />,
content: <InstallmentPaymentMethod />,
edit: <InstallmentPaymentMethod />,
canMakePayment: () => true,
ariaLabel: label,
supports: {
features: settings.supports,
}
} )
87 changes: 87 additions & 0 deletions includes/blocks/gateways/omise-block-installment.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;

class Omise_Block_Installment extends AbstractPaymentMethodType {
/**
* The gateway instance.
*/
protected $gateway;

/**
* Payment method name/id/slug.
*
* @var string
*/
protected $name = 'omise_installment';

/**
* Initializes the payment method type.
*/
public function initialize() {
$this->settings = get_option("woocommerce_{$this->name}_settings", []);
$gateways = WC()->payment_gateways->payment_gateways();
$this->gateway = $gateways[$this->name];
}

/**
* Returns if this payment method should be active. If false, the scripts will not be enqueued.
*
* @return boolean
*/
public function is_active() {
return $this->gateway->is_available();
}

/**
* Returns an array of scripts/handles to be registered for this payment method.
*
* @return array
*/
public function get_payment_method_script_handles() {
if (!wp_script_is("wc-{$this->name}-payments-blocks", 'enqueued')) {
$script_asset = require __DIR__ . "/../assets/js/build/{$this->name}.asset.php";
wp_register_script(
"wc-{$this->name}-payments-blocks",
plugin_dir_url(__DIR__) . "assets/js/build/{$this->name}.js",
$script_asset['dependencies'],
$script_asset['version'],
true
);

wp_enqueue_script("wc-{$this->name}-payments-blocks");
}

return ["wc-{$this->name}-payments-blocks"];
}

/**
* Returns an array of key=>value pairs of data made available to the payment methods script.
*
* @return array
*/
public function get_payment_method_data() {
if (!is_checkout()) {
return [];
}

$data = $this->gateway->get_view_data();
$installment_backends = [];

foreach($data['installment_backends'] as $backend) {
$installment_backends[] = (array)$backend;
}

return [
'name' => $this->name,
'title' => $this->get_setting('title'),
'description' => $this->get_setting('description'),
'supports' => array_filter($this->gateway->supports, [$this->gateway, 'supports']),
'data' => [
'is_zero_interest' => $data['is_zero_interest'],
'installment_min_limit' => $data['installment_min_limit'],
'installment_backends' => $installment_backends,
]
];
}
}
1 change: 1 addition & 0 deletions includes/blocks/omise-block-payments.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class Omise_Block_Payments {
Omise_Block_Paypay::class,
Omise_Block_RabbitLinePay::class,
Omise_Block_Mobile_Banking::class,
Omise_Block_Installment::class,
];

function __construct($container) {
Expand Down
28 changes: 17 additions & 11 deletions includes/gateway/class-omise-payment-installment.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,26 +69,31 @@ public function payment_fields()
{
parent::payment_fields();

Omise_Util::render_view(
'templates/payment/form-installment.php',
$this->get_view_data()
);
}

public function get_view_data()
{
$currency = get_woocommerce_currency();
$cart_total = $this->getTotalAmount();
$cart_total = $this->get_total_amount();

$capabilities = $this->backend->capabilities();
$installmentMinLimit = $capabilities->getInstallmentMinLimit();

Omise_Util::render_view(
'templates/payment/form-installment.php',
array(
'installment_backends' => $this->backend->get_available_providers($currency, $cart_total),
'is_zero_interest' => $capabilities ? $capabilities->is_zero_interest() : false,
'installment_min_limit' => number_format(Omise_Money::convert_currency_unit($installmentMinLimit, $currency))
)
);
return [
'installment_backends' => $this->backend->get_available_providers($currency, $cart_total),
'is_zero_interest' => $capabilities ? $capabilities->is_zero_interest() : false,
'installment_min_limit' => number_format(Omise_Money::convert_currency_unit($installmentMinLimit, $currency))
];
}

/**
* Get the total amount of an order
*/
public function getTotalAmount()
public function get_total_amount()
{
global $wp;

Expand Down Expand Up @@ -116,7 +121,8 @@ public function charge($order_id, $order)

public function get_charge_request($order_id, $order)
{
$source_type = $_POST['source']['type'];
// Prior to WC blocks, we get source as array. With WC blocks, source is now a string.
$source_type = is_array($_POST['source']) ? $_POST['source']['type'] : $_POST['source'];
$source_type = isset($source_type) ? $source_type : '';
$requestData = $this->build_charge_request(
$order_id,
Expand Down
1 change: 1 addition & 0 deletions omise-woocommerce.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ public function block_init()
require_once __DIR__ . '/includes/blocks/gateways/omise-block-paypay.php';
require_once __DIR__ . '/includes/blocks/gateways/omise-block-rabbit-linepay.php';
require_once __DIR__ . '/includes/blocks/gateways/omise-block-mobilebanking.php';
require_once __DIR__ . '/includes/blocks/gateways/omise-block-installment.php';
Omise_Block::init();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public function get_total() {
$GLOBALS['wp'] = $wp;

$installment = new Omise_Payment_Installment();
$total = $installment->getTotalAmount();
$total = $installment->get_total_amount();

$this->assertEquals($total, 999999);

Expand All @@ -65,7 +65,7 @@ function WC() {
}

$installment = new Omise_Payment_Installment();
$total = $installment->getTotalAmount();
$total = $installment->get_total_amount();

$this->assertEquals($total, 999999);
}
Expand Down
1 change: 1 addition & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ module.exports = {
'credit_card': '/includes/blocks/assets/js/omise-credit-card.js',
'omise-one-click-apms': '/includes/blocks/assets/js/omise-one-click-apms.js',
'omise-mobilebanking': '/includes/blocks/assets/js/omise-mobilebanking.js',
'omise_installment': '/includes/blocks/assets/js/omise-installment.js',
},
output: {
path: path.resolve( __dirname, 'includes/blocks/assets/js/build' ),
Expand Down
Loading