Skip to content

Commit

Permalink
Merge pull request #59 from retainful/afterpay_integration
Browse files Browse the repository at this point in the history
Afterpay integration
  • Loading branch information
rameshelamathi authored Jul 26, 2022
2 parents bfd6df4 + fdbbf65 commit c78f9c0
Show file tree
Hide file tree
Showing 6 changed files with 268 additions and 1 deletion.
54 changes: 54 additions & 0 deletions src/Api/AbandonedCart/Checkout.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,60 @@ function generateNocCouponForManualOrders()
return apply_filters('rnoc_generate_noc_coupon_for_manual_orders', $need_noc_coupon, $this);
}

function changeWebHookHeader($http_args, $order_id, $webhook_id){
$stored_webhook_id = self::$settings->getWebHookId();
if( $stored_webhook_id <= 0 || $webhook_id <= 0 || ($stored_webhook_id != $webhook_id) || !class_exists('WC_Webhook')){
return $http_args;
}
try {
$webhook = new \WC_Webhook( $webhook_id );
$delivery_url = $webhook->get_delivery_url();
$topic = $webhook->get_topic();
if($delivery_url != 'https://api.retainful.com/v1/woocommerce/webhooks/checkout' || $topic != 'order.updated' || $order_id <= 0){
return $http_args;
}

$order = self::$woocommerce->getOrder($order_id);
$order_obj = new Order();
$cart_token = self::$woocommerce->getOrderMeta($order, $this->cart_token_key_for_db);
//$logger = wc_get_logger();
if(empty($cart_token)){
//Need to generate cart_token
$cart_token = $this->generateCartToken();
self::$woocommerce->setOrderMeta($order_id, $this->cart_token_key_for_db, $cart_token);
// $logger->add('Retainful','Generate toeken: '.$cart_token);
}
$order_data = $order_obj->getOrderData($order);
// $logger->add('Retainful','Order Data:'.json_encode($order_data));
if(!empty($cart_token) && $order_data){
$client_ip = self::$woocommerce->getOrderMeta($order, $this->user_ip_key_for_db);
$token = self::$woocommerce->getOrderMeta($order, $this->cart_token_key_for_db);
$app_id = self::$settings->getApiKey();
$extra_headers = array(
"X-Client-Referrer-IP" => (!empty($client_ip)) ? $client_ip : null,
"X-Retainful-Version" => RNOC_VERSION,
"X-Cart-Token" => $token,
"Cart-Token" => $token,
"app-id" => $app_id,
"app_id" => $app_id,
"Content-Type" => 'application/json'
);
foreach ($extra_headers as $key => $value){
$http_args['headers'][$key] = $value;
}
//$logger->add('Retainful','App id:'.$app_id);
$cart_hash = $this->encryptData($order_data);
$body = array(
'data' => $cart_hash
);
$http_args['body'] = trim( wp_json_encode( $body ) );
}
}catch (Exception $e){

}
return $http_args;
}

/**
* Sync the order with API
* @param $order_id
Expand Down
8 changes: 8 additions & 0 deletions src/Main.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Rnoc\Retainful\Api\AbandonedCart\RestApi;
use Rnoc\Retainful\Api\NextOrderCoupon\CouponManagement;
use Rnoc\Retainful\Api\Referral\ReferralManagement;
use Rnoc\Retainful\Integrations\AfterPay;
use Rnoc\Retainful\Integrations\Currency;

class Main
Expand Down Expand Up @@ -148,6 +149,7 @@ function activateEvents()
add_action('wp_ajax_rnoc_get_search_coupon', array($this->admin, 'getSearchedCoupons'));
add_action('wp_ajax_rnoc_disconnect_license', array($this->admin, 'disconnectLicense'));
add_action('wp_ajax_rnoc_save_settings', array($this->admin, 'saveAcSettings'));
add_filter('wp_ajax_rnoc_create_order_update_webhook',array($this->admin,'saveNewWebhook'),10);
add_action('wp_ajax_rnoc_save_noc_settings', array($this->admin, 'saveNocSettings'));
add_action('wp_ajax_rnoc_save_premium_addon_settings', array($this->admin, 'savePremiumAddOnSettings'));
add_action('wp_ajax_rnoc_delete_expired_coupons', array($this->admin, 'deleteUnusedExpiredCoupons'));
Expand All @@ -159,6 +161,7 @@ function activateEvents()
}
//initialise currency helper
new Currency();

if ($this->admin->isNextOrderCouponEnabled()) {
//Get events
add_action('woocommerce_checkout_update_order_meta', array($this->rnoc, 'createNewCoupon'), 10, 2);
Expand Down Expand Up @@ -271,8 +274,13 @@ function activateEvents()
// handle placed orders
add_action('woocommerce_order_status_changed', array($checkout, 'orderUpdated'), 11, 1);
add_action('woocommerce_update_order', array($checkout, 'orderUpdated'), 10, 1);
add_filter('woocommerce_webhook_http_args',array($checkout,'changeWebHookHeader'),10,3);
//Todo: multi currency and multi lingual
#add_action('wp_login', array($this->abandoned_cart_api, 'userCartUpdated'));
if($this->admin->isAfterPayEnabled()){
new AfterPay();
}

} else {
if (is_admin()) {
$connect_txt = (!empty($secret_key) && !empty($app_id)) ? __('connect', RNOC_TEXT_DOMAIN) : __('re-connect', RNOC_TEXT_DOMAIN);
Expand Down
68 changes: 67 additions & 1 deletion src/admin/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -830,7 +830,49 @@ function saveAcSettings()
update_option($this->slug . '_settings', $data);
wp_send_json_success(__('Settings successfully saved!', RNOC_TEXT_DOMAIN));
}

function saveNewWebhook(){
$nonce = self::$input->post_get('security','');
if (!wp_verify_nonce($nonce, 'rnoc_create_order_webhook')) {
wp_send_json(array('success' => false,'message' => __('Invalid nonce',RNOC_TEXT_DOMAIN)));
}
$webhook_id = $this->getWebHookId();
if( $webhook_id > 0 ){
wp_send_json(array('success' => true,'message' => __('Webhook already exits',RNOC_TEXT_DOMAIN)));
}
if(!class_exists('WC_Webhook')) {
wp_send_json(array('success' => false,'message' => __('Webhook class not found',RNOC_TEXT_DOMAIN)));
}
try {
$webhook = new \WC_Webhook( $webhook_id );
$name = sanitize_text_field( wp_unslash( 'Retainful Order Update' ) );
$webhook->set_name($name);
if ( ! $webhook->get_user_id() ) {
$webhook->set_user_id( get_current_user_id() );
}
//
$webhook->set_status('active');
$webhook->set_delivery_url( 'https://api.retainful.com/v1/woocommerce/webhooks/checkout' );
$secret = wp_generate_password( 50, true, true );
$webhook->set_secret( $secret );
$topic = 'order.updated';
if ( wc_is_webhook_valid_topic( $topic ) ) {
$webhook->set_topic( $topic );
}
// API version.
$rest_api_versions = wc_get_webhook_rest_api_versions();
$webhook->set_api_version( end( $rest_api_versions ) ); // WPCS: input var okay, CSRF ok.
$webhook_id = $webhook->save();
if($webhook_id > 0) {
$this->saveWebhookId($webhook_id);
$response = array('success' => true,'message' => __('Webhook created successfully',RNOC_TEXT_DOMAIN));
}else{
$response = array('success' => false,'message' => __('Webhook creation failed',RNOC_TEXT_DOMAIN));
}
wp_send_json($response);
}catch (\Exception $e){
wp_send_json(array('success' => false,'message' => __('Webhook creation failed',RNOC_TEXT_DOMAIN)));
}
}
/**
* retainful ac settings page
*/
Expand All @@ -853,6 +895,7 @@ function retainfulSettingsPage()
RNOC_PLUGIN_PREFIX . 'ignored_ip_addresses' => '',
RNOC_PLUGIN_PREFIX . 'enable_debug_log' => '0',
RNOC_PLUGIN_PREFIX . 'handle_storage_using' => 'woocommerce',
RNOC_PLUGIN_PREFIX . 'enable_afterpay_action' => 'no',
RNOC_PLUGIN_PREFIX . 'varnish_check' => 'no',
);
$settings = wp_parse_args($settings, $default_settings);
Expand Down Expand Up @@ -1272,6 +1315,12 @@ function needEmbededReferralWidget()
return apply_filters("enable_embeded_referral_widget", ($need_widget === "yes"));
}

function isAfterPayEnabled(){
$settings = $this->getAdminSettings();
$need_afterpay = (isset($settings[RNOC_PLUGIN_PREFIX . 'enable_afterpay_action']) && !empty($settings[RNOC_PLUGIN_PREFIX . 'enable_afterpay_action'])) ? $settings[RNOC_PLUGIN_PREFIX . 'enable_afterpay_action'] : 'no';
return apply_filters("retainful_enable_afterpay_action", ($need_afterpay === "yes"));
}

/**
* get the cart tracking engine
* @return mixed|string
Expand Down Expand Up @@ -1710,6 +1759,23 @@ function getSecretKey()
return NULL;
}

function getWebHookId() {
$settings = get_option($this->slug, array());
if (isset($settings[RNOC_PLUGIN_PREFIX . 'webhook_id']) && $settings[RNOC_PLUGIN_PREFIX . 'webhook_id'] > 0) {
$webhook = new \WC_Webhook( $settings[RNOC_PLUGIN_PREFIX . 'webhook_id'] );
return method_exists($webhook,'get_id') ? ($webhook->get_id() > 0 ? $settings[RNOC_PLUGIN_PREFIX . 'webhook_id']: 0): 0;
}
return 0;
}

function saveWebhookId($id){
$settings = get_option($this->slug, array());
if($id > 0){
$settings[RNOC_PLUGIN_PREFIX . 'webhook_id'] = $id;
}
update_option($this->slug,$settings);
}

/**
* Check the site has multi currency
* @return bool
Expand Down
25 changes: 25 additions & 0 deletions src/admin/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,31 @@
});
$(this).attr('disabled', false);
});
$(document).on('click', '#generate-webhook-btn', function (event){
event.preventDefault();
var action = $(this).data('action');
var security = $(this).data('security');
var url = retainful_admin.ajax_endpoint.replace("{{action}}", action).replace("{{security}}", security);
$(this).attr('disabled', true);
$.ajax({
url: url,
type: 'POST',
async: false,
dataType: "json",
data: {},
success: function (response) {
if(response.success) {
alert(response.message);
}else {
alert(response.message);
}
},
error: function () {
alert('Please try again later.');
}
});
$(this).attr('disabled', false);
});
$(document).on('submit', '#retainful-settings-form', function (event) {
event.preventDefault();
let submit = $(this).find(':submit');
Expand Down
37 changes: 37 additions & 0 deletions src/admin/templates/pages/settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,31 @@
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="<?php echo RNOC_PLUGIN_PREFIX . 'enable_afterpay_action'; ?>"><?php
esc_html_e('Enable AfterPay Payment Action ?', RNOC_TEXT_DOMAIN);
?></label>
</th>
<td>
<label>
<input name="<?php echo RNOC_PLUGIN_PREFIX . 'enable_afterpay_action'; ?>" type="radio"
id="<?php echo RNOC_PLUGIN_PREFIX . 'enable_afterpay_action_yes'; ?>"
value="yes" <?php if ($settings[RNOC_PLUGIN_PREFIX . 'enable_afterpay_action'] == 'yes') {
echo "checked";
} ?>>
<?php esc_html_e('Yes', RNOC_TEXT_DOMAIN); ?>
</label>
<label>
<input name="<?php echo RNOC_PLUGIN_PREFIX . 'enable_afterpay_action'; ?>" type="radio"
id="<?php echo RNOC_PLUGIN_PREFIX . 'enable_afterpay_action_no'; ?>"
value="no" <?php if ($settings[RNOC_PLUGIN_PREFIX . 'enable_afterpay_action'] == 'no') {
echo "checked";
} ?>>
<?php esc_html_e('No', RNOC_TEXT_DOMAIN); ?>
</label>
</td>
</tr>
<tr>
<th scope="row">
<label for="<?php echo RNOC_PLUGIN_PREFIX . 'varnish_check'; ?>"><?php
Expand Down Expand Up @@ -433,6 +458,18 @@
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="<?php echo RNOC_PLUGIN_PREFIX . 'webhook_id'; ?>"><?php
esc_html_e('Order Update Webhook', RNOC_TEXT_DOMAIN);
?></label>
</th>
<td>
<button type="button" id="generate-webhook-btn" data-action="rnoc_create_order_update_webhook"
data-security="<?php echo wp_create_nonce('rnoc_create_order_webhook') ?>"
class="button"><?= __('Create WebHook', RNOC_TEXT_DOMAIN) ?></button>
</td>
</tr>
<tr>
<th>
</th>
Expand Down
77 changes: 77 additions & 0 deletions src/integrations/AfterPay.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

namespace Rnoc\Retainful\Integrations;

use Rnoc\Retainful\Api\AbandonedCart\Checkout;
use Rnoc\Retainful\WcFunctions;

class AfterPay
{
/** @var int the Afterpay quote id */
private $quote_id;

/** @var array key-value pairs of jilt meta */
private $retainful_meta = array();

function __construct()
{
add_action('save_post_afterpay_quote', array($this, 'saveAfterPayData'), 10, 3);
add_action('before_delete_post', array($this, 'captureRetainfulDataFromQuote'));
add_action('woocommerce_new_order', array($this, 'saveRetainfulDataToOrder'));
}

function saveAfterPayData($post_id, $post, $update)
{
if ($update || !$this->isPluginActive()) {
return;
}
$checkout = new Checkout();
if ($checkout->isPendingRecovery()) {
$checkout->markOrderAsPendingRecovery();
}
$cart_token = $checkout->getCartToken();
if ($cart_token) {
$checkout->setOrderCartToken($cart_token, $post_id);
}
}

function captureRetainfulDataFromQuote($post_id)
{
if(!$this->isPluginActive()){
return;
}
$post = get_post($post_id);
if (isset($post->post_type) && 'afterpay_quote' === $post->post_type) {
$this->quote_id = (int)$post_id;
$post_meta = get_post_meta($post_id, '', true);
foreach ($post_meta as $key => $value) {
if (0 === strpos($key, '_rnoc')) {
$this->retainful_meta[$key] = isset($value[0]) && !empty($value[0]) ? $value[0]: '';
}
}
}
}

function saveRetainfulDataToOrder($order_id){
if(!$this->isPluginActive()){
return;
}
if ( $order_id > 0 && (int)$order_id === $this->quote_id ) {
$wc_function = new WcFunctions();
foreach ( $this->retainful_meta as $key => $value ) {
$wc_function->setOrderMeta($order_id,$key,$value);
}
}
}


function isPluginActive()
{
$active_plugins = apply_filters('active_plugins', get_option('active_plugins', array()));
if (is_multisite()) {
$active_plugins = array_merge($active_plugins, get_site_option('active_sitewide_plugins', array()));
}
return in_array('afterpay-gateway-for-woocommerce/afterpay-gateway-for-woocommerce.php', $active_plugins, false) || array_key_exists('afterpay-gateway-for-woocommerce/afterpay-gateway-for-woocommerce.php', $active_plugins);
}

}

0 comments on commit c78f9c0

Please sign in to comment.