| Server IP : 13.126.101.145 / Your IP : 216.73.217.33 Web Server : Apache/2.4.52 (Ubuntu) System : Linux ip-11-115-0-196 6.8.0-1039-aws #41~22.04.1-Ubuntu SMP Thu Sep 11 10:54:48 UTC 2025 x86_64 User : www-data ( 33) PHP Version : 8.3.17 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /var/www/html/rentals_updated/wp-content/plugins/woocommerce-billdesk-plugin/ |
Upload File : |
<?php
/*
* Plugin Name: BillDesk for WooCommerce
* Plugin URI: https://www.billdesk.com
* Description: BillDesk Payment Integration for WooCommerce
* Version: 1.0.9-c62e892
* Stable tag: 1.0.0
* Author: Team BillDesk
* Author URI: https://www.billdesk.com
*/
use io\billdesk\client\hmacsha256\BillDeskJWEHS256Client;
use io\billdesk\client\hmacsha256\JWEHS256Helper;
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly
}
require_once ABSPATH . 'wp-admin/includes/plugin.php';
if (file_exists(dirname(__FILE__) . '/vendor/autoload.php')) {
require_once dirname(__FILE__) . '/vendor/autoload.php';
}
require_once dirname(__FILE__) . '/logger.php';
require_once dirname(__FILE__) . '/connect.php';
error_reporting(0);
//ini_set('display_errors','Off');
/**
* Function to Activate BillDesk WooCommerce plugin.
*/
function activate_bdskwoo_plugin()
{
$logger = WooBillDeskLogger::logger("activation");
$logger->info("Activating BillDesk WooCommerce Plugin");
add_filter('generate_rewrite_rules', 'woo_templates_rewrite');
flush_rewrite_rules(false);
global $table_prefix, $wpdb;
$tblname = 'woo_bldsk_order';
$wp_order_table = $table_prefix . "$tblname ";
#Check to see if the table exists already, if not, then create it
if ($wpdb->get_var("show tables like '$wp_order_table'") != $wp_order_table) {
$logger->info("Creating table $wp_order_table for maintaining BillDesk specific transaction data");
$sql = "CREATE TABLE $wp_order_table (
`id` int(11) NOT NULL AUTO_INCREMENT,
`transaction_data` text DEFAULT NULL,
`order_id` text DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
require_once(ABSPATH . '/wp-admin/includes/upgrade.php');
dbDelta($sql);
}
$logger->info("BillDesk WooCommerce Plugin activated.");
}
register_activation_hook(__FILE__, 'activate_bdskwoo_plugin');
/**
* Add a rewrite rule to billdesk childwindow autoclose include endpoint.
* @param instance $wp_rewrite global variable.
*/
function woo_templates_rewrite($wp_rewrite)
{
$wp_rewrite->rules = array_merge(
array(
'index.php/woo/billdesk/woo_autoclose/?$' => 'index.php?woo_bdsk_action=woo_autoclose'
),
$wp_rewrite->rules
);
}
/**
* Add new query vars.
* @param array $query_vars Query vars.
* @return string[]
*/
function woo_query_vars($query_vars)
{
$query_vars[] = 'woo_bdsk_action';
return $query_vars;
}
/**
* Includes childwindow autoclose template.
*/
function woo_template_redirection()
{
$logger = WooBillDeskLogger::defaultLogger();
$action = get_query_var('woo_bdsk_action');
//$logger->debug("Found woo_bdsk_action: $action");
if ($action && $action === "woo_autoclose") {
include plugin_dir_path(__FILE__) . 'includes/woo_autoclose.php';
die;
}
}
add_action('plugins_loaded', 'woocommerce_billdesk_init', 0);
/**
* Initialize BIlldesk WooCommerce payment gateway.
*/
function woocommerce_billdesk_init()
{
$logger = WooBillDeskLogger::defaultLogger();
if (!class_exists('WC_Payment_Gateway')) {
$logger->error("Unable to find class WC_Payment_Gateway. WooCommerce plugin is not installed?");
return;
}
add_filter('generate_rewrite_rules', 'woo_templates_rewrite');
add_filter('query_vars', 'woo_query_vars');
add_filter('template_redirect', 'woo_template_redirection');
class WC_Billdesk extends WC_Payment_Gateway
{
const SESSION_KEY = 'billdesk_wc_order_id';
const BILLDESK_PAYMENT_ID = 'billdesk_payment_id';
const BILLDESK_ORDER_ID = 'billdesk_order_id';
const BILLDESK_SIGNATURE = 'billdesk_signature';
const BILLDESK_WC_FORM_SUBMIT = 'billdesk_wc_form_submit';
const INR = 'INR';
const CAPTURE = 'capture';
const AUTHORIZE = 'authorize';
const WC_ORDER_ID = 'woocommerce_order_id';
const DEFAULT_LABEL = 'Credit Card/Debit Card/NetBanking';
const DEFAULT_DESCRIPTION = 'Pay securely by Credit or Debit card or Internet Banking through BillDesk.';
const DEFAULT_SUCCESS_MESSAGE = 'Thank you for shopping with us. Your account has been charged and your transaction is successful. We will be processing your order soon.';
protected $visibleSettings = array(
'child_window_enabled',
'title',
'description',
'merchant_logo',
'merchant_id',
'merchant_key',
'client_id',
'item_code',
'environment',
'merchant_logo',
'retry_count',
'payment_category',
'order_success_message',
'order_summery_page_display',
'site_url'
);
public $form_fields = array();
public $supports = array(
'products',
'refunds'
);
/**
* Can be set to true if you want payment fields
* to show on the checkout (if doing a direct integration).
* @var boolean
*/
public $has_fields = false;
/**
* Unique ID for the gateway
* @var string
*/
public $id = 'billdesk';
/**
* Title of the payment method shown on the admin page.
* @var string
*/
public $method_title = 'BillDesk';
/**
* Description of the payment method shown on the admin page.
* @var string
*/
public $method_description = 'Allow customers to securely pay via BillDesk (Credit/Debit Cards, NetBanking, UPI, Wallets)';
/**
* Icon URL, set in constructor
* @var string
*
*/
public $icon;
public function getSetting($key)
{
return $this->get_option($key);
}
// Load the order success message.
public function getCustomOrdercreationMessage()
{
$message = $this->getSetting('order_success_message');
if (isset($message) === false) {
$message = static::DEFAULT_SUCCESS_MESSAGE;
}
return $message;
}
/**
* @param boolean $hooks Whether or not to
* setup the hooks on
* calling the constructor
*/
public function __construct()
{
$logger = WooBillDeskLogger::logger("WC_Billdesk");
// NOTE: Only intention of this appears to be able to override the logo of BillDesk. Good to have feature.
$this->icon = apply_filters('woocommerce_billdesk_icon', plugins_url('assets/logo.svg', __FILE__));
$this->init_form_fields();
$this->init_settings();
$this->initHooks();
$this->title = $this->getSetting('title');
}
protected function initHooks()
{
add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
add_action('woocommerce_thankyou_' . $this->id, array($this, 'thankyou_page'));
add_action('woocommerce_api_' . $this->id, array($this, 'check_billdesk_response'));
add_action('woocommerce_checkout_init', array($this, 'woocommerce_checkout_init'));
add_filter('woocommerce_thankyou_order_received_text', array($this, 'getCustomOrdercreationMessage'));
$cb = array($this, 'process_admin_options');
if (version_compare(WOOCOMMERCE_VERSION, '2.0.0', '>=')) {
add_action("woocommerce_update_options_payment_gateways_{$this->id}", $cb);
} else {
add_action('woocommerce_update_options_payment_gateways', $cb);
}
}
/**
* Add a woocommerce notification message
*
* @param string $message Notification message
* @param string $type Notification type, default = notice
*/
protected function add_notice($message, $type = 'notice')
{
global $woocommerce;
$type = in_array($type, array('notice', 'error', 'success'), true) ? $type : 'notice';
if (function_exists('wc_add_notice')) {
wc_add_notice($message, $type);
} else {
switch ($type) {
case "error":
$woocommerce->add_error($message);
break;
default:
$woocommerce->add_message($message);
break;
}
}
}
/**
* Initialize BIlldesk form fields.
*/
public function init_form_fields()
{
$defaultFormFields = array(
'child_window_enabled' => array(
'title' => __('Child Window', $this->id),
'type' => 'checkbox',
'label' => __(' ', $this->id),
'default' => 'yes'
),
'title' => array(
'title' => __('Title', $this->id),
'type' => 'text',
'description' => __('This controls the title which the user sees during checkout.', $this->id),
'default' => __(static::DEFAULT_LABEL, $this->id)
),
'description' => array(
'title' => __('Description', $this->id),
'type' => 'textarea',
'description' => __('This controls the description which the user sees during checkout.', $this->id),
'placeholder' => $test_placeholder = __('Enter description ', $this->id),
'default' => __(static::DEFAULT_DESCRIPTION, $this->id)
),
'merchant_id' => array(
'title' => __('Merchant Id*', $this->id),
'type' => 'text',
'placeholder' => $test_placeholder = __('Enter Merchant Id ', $this->id),
'description' => __('The merchant Id', $this->id)
),
'merchant_key' => array(
'title' => __('Merchant Key*', $this->id),
'type' => 'password',
'placeholder' => $test_placeholder = __('Enter merchant_key ', $this->id),
'description' => __('The Merchant Key.', $this->id)
),
'client_id' => array(
'title' => __('Client Id*', $this->id),
'type' => 'text',
'placeholder' => $test_placeholder = __('Enter Client Id ', $this->id),
'description' => __('The Client Id.', $this->id)
),
'item_code' => array(
'title' => __('Item code*', $this->id),
'type' => 'text',
'placeholder' => $test_placeholder = __('Enter Item code ', $this->id),
'description' => __('The Item Code.', $this->id)
),
'merchant_logo' => array(
'title' => __('Merchant Logo', $this->id),
'type' => 'text',
'placeholder' => $test_placeholder = __('Enter Merchant Logo ', $this->id),
'description' => __('The merchant Logo', $this->id)
),
'payment_category' => array(
'title' => __('Payment Categories', $this->id),
'type' => 'text',
'placeholder' => $test_placeholder = __('Enter Payment Categories ', $this->id),
'description' => __('The Payment Categories', $this->id)
),
'retry_count' => array(
'title' => __('Retry Count*', $this->id),
'type' => 'select',
'description' => __('Retry Count', $this->id),
'default' => 0,
'options' => array(
0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 10
)
),
'environment' => array(
'title' => __('Environment*', $this->id),
'type' => 'select',
'description' => __('Environment', $this->id),
'default' => 'UAT',
'options' => array(
'UAT' => 'UAT',
'PROD' => 'PROD'
)
),
'order_success_message' => array(
'title' => __('Order Completion Message', $this->id),
'type' => 'textarea',
'description' => __('Message to be displayed after a successful order', $this->id),
'default' => __(static::DEFAULT_SUCCESS_MESSAGE, $this->id),
),
/*
'order_summery_page_display' => array(
'title' => __('Show order summery page', $this->id),
'type' => 'checkbox',
'description' => __('If this option is enabled, An order summary page is displayed and user has to click on payment button to launch SDK.', $this->id),
'default' => 'no'
), */
'site_url' => array(
//'title' => __('Order Completion Message', $this->id),
'type' => 'hidden',
// 'description' => __(get_option('siteurl'), $this->id),
'default' => __(get_option('siteurl'), $this->id),
),
);
foreach ($defaultFormFields as $key => $value) {
if (in_array($key, $this->visibleSettings, true)) {
$this->form_fields[$key] = $value;
}
}
}
public function admin_options()
{
echo '<h3>' . __('BillDesk Payment Integration', $this->id) . '</h3>';
echo '<p>' . __('Allows payments by Credit/Debit Cards, NetBanking, UPI, and multiple Wallets') . '</p>';
echo '<table class="form-table">';
// Generate the HTML For the settings form.
$this->generate_settings_html();
echo '</table>';
echo '<table class="form-table"><tr>';
echo '<p><button type="test_connectivity" id="test_connectivity" class="button button-primary left" value="Test Connectivity" >Test PG Connectivity</button>';
echo '<div id="show_error" style="margin: 20px auto; color: crimson;" >
</div>';
echo '<div id="show_mess" style="margin: 20px auto; color: #147c3c" >
</div></p>';
echo '</tr></table>';
}
public function get_description()
{
return $this->getSetting('description');
}
// added woocommerce_checkout_init action ,Gets the main WC_Checkout Instance.
public function woocommerce_checkout_init($order)
{
$log = WooBillDeskLogger::logger("woocommerce_checkout_init");
//$log->info("woocommerce_checkout_init " json_encode($order) );
$orderId = (isset($_GET['order_id'])) ? $_GET['order_id'] : null;
$log->info("Checkout Error order $orderId" );
$wooorderid = (isset($_POST['wooorderid'])) ? $_POST['wooorderid'] : null;
error_log("Inside check_billdesk_response $wooorderid : " . $wooorderid . PHP_EOL, 0);
global $table_prefix, $wpdb;
$tblname = 'woo_bldsk_order';
$wp_order_table = $table_prefix . "$tblname ";
$query = $wpdb->prepare(
"SELECT *
FROM $wp_order_table
WHERE order_id = %s ORDER BY id DESC LIMIT 1",
$orderId
);
$result = $wpdb->get_results($query);
if (count($result) <= 0) {
return;
}
$txn = json_decode(($result[0])->transaction_data);
//$log->info("Checkout Error TXN $txn" );
if ($txn == null) {
$error = 'Payment was cancelled by the user.';
}
else if(!empty(($txn->error_code))) {
$log->info("Checkout Error order Inside 2nd IF" );
$error = $txn->error_code ." : " . $txn->message;
}
else {
$log->info("Checkout Error order Inside Else" );
$error = $txn->transaction_error_code . " : " . $txn->transaction_error_desc;
}
echo '<div class="entry-content"><div class="woocommerce"><ul class="woocommerce-notices-wrapper" style="margin-top:20%">
<li class="woocommerce-error">
ERROR-MESSAGE: <strong> ' . $error . ' </strong>
</li>
</ul></div></div>';
}
/**
* Receipt Page
* @param string $orderId WC Order Id
**/
protected function billdesk_response($orderId)
{
global $woocommerce, $wp_version;
$log = WooBillDeskLogger::logger("Create Order");
$order = new WC_Order($orderId);
$log->info("billdesk_response order $order" );
$log->info("Creating order");
try {
$merchantid = $this->getSetting('merchant_id');
$merchantkey = $this->getSetting('merchant_key');
$clientid = $this->getSetting('client_id');
$currency_value = $order->get_currency();
// TODO: Need to create a list of all supported currencies or list of all ISO currencies
try{
// $arr = "";
$arr = array(
'INR' => '356' ,'USD' => '840','GBP' => '826', 'EUR' => '978', 'AED' => '784'
);
// FIXME: Possibility of currency being null at this point.
// If we have all the currencies in the table, this will lead to
// error from PG which is a more appropriate scenario.
//
$iteamcode = $this->getSetting('item_code');
$amount = $order->get_total();
$childwindow = $this->getSetting('child_window_enabled');
$log->debug("Child window enabled: $childwindow");
$ip = getenv('HTTP_CLIENT_IP') ?:
getenv('HTTP_X_FORWARDED_FOR') ?:
getenv('HTTP_X_FORWARDED') ?:
getenv('HTTP_FORWARDED_FOR') ?:
getenv('HTTP_FORWARDED') ?:
getenv('REMOTE_ADDR');
$ipaddress = strtok($ip, ",");
$userAgent = $_SERVER['HTTP_USER_AGENT'];
if ($childwindow == 'yes') {
$ru = get_option('siteurl') . '/index.php/woo/billdesk/woo_autoclose/';
} else {
$ru = $this->getRedirectUrl();
}
$log->debug("Setting RU: $ru");
$environment = $this->getSetting('environment');
$bd_version = "pluginv,1.0.9";
$platform_woocommerce ='platform,woocommerce_'.get_option( 'woocommerce_version', null ).'_Wordpress_'.$wp_version.'-'.$bd_version ;
//$version = get_plugin_data(__FILE__)['Version'];
$log->debug("bd_version: $bd_version");
if ($environment == 'UAT') {
$client = new BillDeskJWEHS256Client('https://uat1.billdesk.com/u2', $clientid, $merchantkey);
}
if ($environment == 'PROD') {
$client = new BillDeskJWEHS256Client('https://api.billdesk.com', $clientid, $merchantkey);
}
$client->setLogger($log);
$request = array(
'mercid' => $merchantid,
'orderid' => uniqid(),
'amount' => $amount,
'order_date' => date_format(new \DateTime(), DATE_W3C),
'currency' => $arr[$currency_value],
'ru' => $ru,
'itemcode' => $iteamcode,
'device' => array(
'init_channel' => 'internet',
'ip' => $ipaddress,
'user_agent' => $userAgent
),
'additional_info' => array(
'additional_info1' => $order->get_id(),
'additional_info2' => $order->get_billing_first_name() . ',' . $order->get_billing_last_name(),
'additional_info3' => $order->get_billing_email(),
'additional_info4' => $order->get_billing_phone(),
'additional_info5' => $order->get_billing_address_1() . ',' . $order->get_billing_city() . ',' . $order->get_billing_postcode() . ',' . $order->get_billing_state() . ',' . $order->get_billing_country(),
'additional_info7' => $platform_woocommerce,
)
);
return $client->createOrder($request);
// }
} catch(Exception $exp){
print("Failed to create order.Currency is not there in list");
return true;
}
} catch (Exception $exp) {
print($exp->getMessage());
return true;
}
// }
}
public function billdesk_refund($orderId, $refundAmount)
{
$log = WooBillDeskLogger::logger("refund_" . $orderId);
global $wpdb;
$result = $wpdb->get_results(
$wpdb->prepare("SELECT transaction_data FROM wp_woo_bldsk_order WHERE order_id = %s", $orderId)
);
$array = json_decode(json_encode($result), true);
$array3 = json_decode($array[0]['transaction_data'], true);
$bldskorderid = $array3['orderid'];
$bldskorder_date = $array3['transaction_date'];
$bldskamount = $array3['amount'];
$bldskcurrency = $array3['currency'];
$bldsktxnid = $array3['transactionid'];
$merchantid = $this->getSetting('merchant_id');
$merchantkey = $this->getSetting('merchant_key');
$clientid = $this->getSetting('client_id');
$environment = $this->getSetting('environment');
if ($environment == 'UAT') {
$client = new BillDeskJWEHS256Client('https://uat1.billdesk.com/u2', $clientid, $merchantkey);
}
if ($environment == 'PROD') {
$client = new BillDeskJWEHS256Client('https://api.billdesk.com', $clientid, $merchantkey);
}
$client->setLogger($log);
$request = array(
'transactionid' => $bldsktxnid,
'orderid' => $bldskorderid,
'mercid' => $merchantid,
'transaction_date' => $bldskorder_date,
'txn_amount' => $bldskamount,
'refund_amount' => $refundAmount,
'currency' => $bldskcurrency,
'merc_refund_ref_no' => uniqid()
);
return $client->refundTransaction($request);
}
/**
* Receipt Page
* @param string $orderId WC Order Id
**/
function receipt_page($orderId)
{
echo $this->generate_billdesk_form($orderId);
}
/**
* Returns key to use in session for storing BillDesk order Id
* @param string $orderId BillDesk Order Id
* @return string Session Key
*/
protected function getOrderSessionKey($orderId)
{
return self::BILLDESK_ORDER_ID . $orderId;
}
/**
* Given a order Id, find the associated
* BillDesk Order from the session and verify
* that is is still correct. If not found
* (or incorrect), create a new BillDesk Order
*
* @param string $orderId Order Id
* @return mixed BillDesk Order Id or Exception
*/
protected function createOrGetBilldeskOrderId($orderId)
{
global $woocommerce;
$sessionKey = $this->getOrderSessionKey($orderId);
$billdeskOrderId = $woocommerce->session->get($sessionKey);
if (($billdeskOrderId === null) or
(($billdeskOrderId and ($this->verifyOrderAmount($billdeskOrderId, $orderId)) === false))
) {
$create = true;
} else {
return $billdeskOrderId;
}
if ($create) {
return $this->createBilldeskOrderId($orderId, $sessionKey);
}
}
/**
* Returns redirect URL post payment processing
* @return string redirect URL
*/
private function getRedirectUrl()
{
return add_query_arg('wc-api', $this->id, trailingslashit(get_home_url()));
}
/**
* Specific payment parameters to be passed to checkout
* for payment processing
* @param string $orderId WC Order Id
* @return array payment params
*/
protected function getBilldeskPaymentParams($orderId)
{
$billdeskOrderId = $this->createOrGetBilldeskOrderId($orderId);
if ($billdeskOrderId === null) {
throw new Exception('BILLDESK ERROR: Billdesk API could not be reached');
} else if ($billdeskOrderId instanceof Exception) {
$message = $billdeskOrderId->getMessage();
throw new Exception("BILLDESK ERROR: Order creation failed with the message: '$message'.");
}
return [
'order_id' => $billdeskOrderId
];
}
/**
* Generate BillDesk button link
* @param string $orderId WC Order Id
**/
public function generate_billdesk_form($orderId)
{
$order = new WC_Order($orderId);
$params = $this->getBilldeskPaymentParams($orderId);
$checkoutArgs = $this->getCheckoutArguments($order, $params);
$html = $this->generateOrderForm($checkoutArgs, $orderId);
return $html;
}
/**
* default parameters passed to checkout
* @param WC_Order $order WC Order
* @return array checkout params
*/
private function getDefaultCheckoutArguments($order)
{
$callbackUrl = $this->getRedirectUrl();
$orderId = $order->get_order_number();
$productinfo = "Order $orderId";
$currency = $order->get_currency();
$mod_version = get_plugin_data(plugin_dir_path(__FILE__) . 'woo-billdesk.php')['Version'];
return array(
'key' => $this->getSetting('key_id'),
'name' => get_bloginfo('name'),
'currency' => $currency,
'description' => $productinfo,
'notes' => array(
'woocommerce_order_id' => $orderId
),
'callback_url' => $callbackUrl,
'prefill' => $this->getCustomerInfo($order),
'_' => array(
'integration' => 'woocommerce',
'integration_version' => $mod_version,
'integration_parent_version' => WOOCOMMERCE_VERSION,
),
);
}
/**
* @param WC_Order $order
* @return string currency
*/
private function getOrderCurrency($order)
{
if (version_compare(WOOCOMMERCE_VERSION, '2.7.0', '>=')) {
return $order->get_currency();
}
return $order->get_order_currency();
}
/**
* Returns array of checkout params
*/
private function getCheckoutArguments($order, $params)
{
$args = $this->getDefaultCheckoutArguments($order);
$currency = $this->getOrderCurrency($order);
$args = array_merge($args, $params);
return $args;
}
public function getCustomerInfo($order)
{
if (version_compare(WOOCOMMERCE_VERSION, '2.7.0', '>=')) {
$args = array(
'name' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
'email' => $order->get_billing_email(),
'contact' => $order->get_billing_phone(),
);
} else {
$args = array(
'name' => $order->billing_first_name . ' ' . $order->billing_last_name,
'email' => $order->billing_email,
'contact' => $order->billing_phone,
);
}
return $args;
}
// Calls the helper function to create order data
protected function createBilldeskOrderId($orderId, $sessionKey)
{
global $woocommerce;
$billdeskOrderId = $orderId;
$woocommerce->session->set($sessionKey, $billdeskOrderId);
$order = wc_get_order($orderId);
$order->add_order_note("Billdesk OrderId: $billdeskOrderId");
return $billdeskOrderId;
}
protected function verifyOrderAmount($billdeskOrderId, $orderId)
{
$order = new WC_Order($orderId);
$orderCreationData = $this->getOrderCreationData($orderId);
$billdeskOrderArgs = array(
'id' => $billdeskOrderId,
'amount' => $orderCreationData['amount'],
'currency' => $orderCreationData['currency'],
'receipt' => (string) $orderId,
);
$orderKeys = array_keys($billdeskOrderArgs);
return true;
}
private function getOrderCreationData($orderId)
{
$order = new WC_Order($orderId);
$info = $this->getCustomerInfo($order);
echo "</br>";
$data = array(
'receipt' => $orderId,
'amount' => (int) round($order->get_total() * 100),
'email' => $info['email'],
'contact' => $info['contact'],
'currency' => $this->getOrderCurrency($order),
'payment_capture' => ($this->getSetting('payment_action') === self::AUTHORIZE) ? 0 : 1,
'app_offer' => ($order->get_discount_total() > 0) ? 1 : 0,
'notes' => array(
self::WC_ORDER_ID => (string) $orderId,
),
);
return $data;
}
// Web SDK JS & CSS
private function enqueueCheckoutScripts($data)
{
$environment = $this->getSetting('environment');
$handle = 'some-handle';
wp_register_script($handle, 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js', array(), '3.5.1');
wp_enqueue_script($handle);
if ($environment == 'UAT') {
wp_enqueue_style('billdesksdk-style', 'https://uat1.billdesk.com/merchant-uat/sdk/dist/billdesksdk/billdesksdk.css', array(), '', '', true);
wp_register_script('billdeskwoo-nomodule', plugin_dir_url(__FILE__) . 'https://uat1.billdesk.com/merchant-uat/sdk/dist/billdesksdk/billdesksdk.js');
wp_add_inline_script(
'billdeskwoo-nomodule',
'',
''
);
wp_enqueue_script('billdeskwoo-nomodule');
wp_enqueue_script('billdeskwoo-module', 'https://uat1.billdesk.com/merchant-uat/sdk/dist/billdesksdk/billdesksdk.esm.js');
} else if ($environment == 'PROD') {
// Web SDK JS & CSS
wp_enqueue_style('billdesksdk-style', 'https://pay.billdesk.com/jssdk/v1/dist/billdesksdk/billdesksdk.css', array(), '', '', true);
wp_register_script('billdeskwoo-nomodule', plugin_dir_url(__FILE__) . 'https://pay.billdesk.com/jssdk/v1/dist/billdesksdk/billdesksdk.js');
wp_add_inline_script(
'billdeskwoo-nomodule',
'',
''
);
wp_enqueue_script('billdeskwoo-nomodule');
wp_enqueue_script('billdeskwoo-module', 'https://pay.billdesk.com/jssdk/v1/dist/billdesksdk/billdesksdk.esm.js');
}
wp_register_script('billdesk_wc_script', plugin_dir_url(__FILE__) . 'script.js');
wp_localize_script(
'billdesk_wc_script',
'billdesk_wc_checkout_vars',
$data
);
wp_enqueue_script('billdesk_wc_script');
}
/**
* Generates the order form
**/
function generateOrderForm($data, $orderId)
{
$redirectUrl = $this->getRedirectUrl();
$cw = $this->getSetting('child_window_enabled');
$merchant_logo = $this->getSetting('merchant_logo');
$payment_category = $this->getSetting('payment_category');
$retry_count = $this->getSetting('retry_count');
$order_summery_page= $this->getSetting('order_summery_page_display');
$data['cancel_url'] = wc_get_checkout_url();
$log = WooBillDeskLogger::logger("Transaction_Responce");
$log->info("Transaction Responce ");
$this->enqueueCheckoutScripts($data);
$createOrder = $this->billdesk_response($orderId);
if ($createOrder == '1') {
return <<<EOT
<div class="woocommerce-notices-wrapper">
<ul class="woocommerce-error" role="alert">
<li> Failed to create order </li>
</ul>
</div>
EOT;
$log->debug("Enter Process Payment the check billdesk response: $createOrder");
} else {
$createOrderResponse = $createOrder->getResponse();
$responseJson = json_encode((array)$createOrderResponse, true);
$codata = $createOrder->getResponseStatus();
$log->debug("Create order response:$codata");
if ($createOrder->getResponseStatus() == 400) {
$errorCode = $createOrder->getResponse()->error_code;
$errorMessage = "Currency not supported";//$createOrder->getResponse()->message;
return <<<EOT
<div class="woocommerce-notices-wrapper">
<ul class="woocommerce-error" role="alert">
<li> Failed to create order, Currency is not supported. </li>
</ul>
</div>
EOT;
}
if ($createOrder->getResponseStatus() == 422) {
$errorCode = $createOrder->getResponse()->error_code;
$errorMessage = $createOrder->getResponse()->message;
return <<<EOT
<div class="woocommerce-notices-wrapper">
<ul class="woocommerce-error" role="alert">
<li> Failed to create order. Error Code: $errorCode, Error Message: $errorMessage </li>
</ul>
</div>
EOT;
}
if ($createOrder->getResponseStatus() != 200) {
$errorCode = $createOrder->getResponse()->error_code;
$errorMessage = $createOrder->getResponse()->message;
return <<<EOT
<div class="woocommerce-notices-wrapper">
<ul class="woocommerce-error" role="alert">
<li> Failed to create order1. Error Code: $errorCode, Error Message: $errorMessage </li>
</ul>
</div>
EOT;
}
else {
return <<<EOT
<form id='billdesk_form' name='billdesk_form' action="$redirectUrl" method="POST">
<input type="hidden" name="txcode" id="txcode">
<input type="hidden" name="osp" id="osp" value='$order_summery_page'>
<input type="hidden" name="wooorderid" id="wooorderid" value="$orderId">
<input type="hidden" name="billdesk_payment_id" id="billdesk_payment_id">
<input type="hidden" name="transaction_response" id="transaction_response" >
<input type="hidden" name="encrypted_response" id="encrypted_response" >
<input type="hidden" name="childWindow" id="childWindow" value='$cw'>
<input type="hidden" name="bldsksdk_merchant_logo" id="merchant_logo" value='$merchant_logo'/>
<input type="hidden" name="payment_category" id="payment_category" value='$payment_category'>
<input type="hidden" name="retry_count" id="retry_count" value='$retry_count'>
<input type="hidden" id="woo-res" name="woo-res" value='$responseJson'/>
<!-- This distinguishes all our various wordpress plugins -->
<input type="hidden" name="billdesk_wc_form_submit" value="1">
</form>
<p id="msg-billdesk-success" class="woocommerce-info woocommerce-message" style="display:none">
Please wait while we are processing your payment.
</p>
<p>Please click the button below to pay with BillDesk.</p><br>
<p>
<!--<button id="btn-billdesk">Pay Now</button> --!>
<button id="btn-billdesk" onclick="InvokeSdk()">Payment</button>
<button id="btn-billdesk-cancel" onclick="document.billdesk_form.submit()">Cancel</button>
</p>
EOT;
}
}
}
/**
* Gets the Order Key from the Order
* for all WC versions that we suport
*/
public function getOrderKey($order)
{
if (version_compare(WOOCOMMERCE_VERSION, '3.0.0', '>=')) {
return $order->get_order_key();
}
return $order->order_key;
}
/**
* Process the Refund payment and return the result
**/
/**
* @var $orderId -> Refunded Order ID
* @var $refundAmount -- Provides the Refund amount
*/
public function process_refund($orderId, $refundAmount = null, $reason = '')
{
$log = WooBillDeskLogger::logger("refund_" . $orderId);
$order = new WC_Order($orderId);
if (!$order or !$order->get_transaction_id()) {
return new WP_Error('error', __('Refund failed: No transaction ID', 'woocommerce'));
}
$response = $this->billdesk_refund($orderId, $refundAmount);
$responseBody = $response->getResponse();
if ($response->getResponseStatus() != 200) {
$log->error(
"Refund request failed",
array(
"status" => $response->getResponseStatus(),
"response" => json_encode($responseBody)
)
);
$order->add_order_note(__('Refund failed due to error code: ' . $responseBody->error_code . " error message: " . $responseBody->message, 'woocommerce'));
return false;
}
$refundResult = true;
if ($responseBody->refund_status === "0699" || $responseBody->refund_status === "0799") {
$order->add_order_note(
__(
'Refund Successful! BillDesk Refund Id: ' . $responseBody->refundid . ' Refund Amount: ' . $responseBody->refund_amount,
'woocommerce'
)
);
} else {
// TODO: Need to check what are the other statuses apart from 0699 and 0799
$order->add_order_note(__('Refund Failed!', 'woocommerce'));
$refundResult = false;
}
return $refundResult;
}
/**
* Process the payment and return the result
* @var $orderId -> Process Order ID
**/
function process_payment($order_id)
{
$logger = WooBillDeskLogger::logger("process_payment");
$logger->info("Process Payment, billdesk response: $order_id");
global $woocommerce;
$order = new WC_Order($order_id);
$woocommerce->session->set(self::SESSION_KEY, $order_id);
$orderKey = $this->getOrderKey($order);
if (version_compare(WOOCOMMERCE_VERSION, '2.1', '>=')) {
return array(
'result' => 'success',
'redirect' => add_query_arg('key', $orderKey, $order->get_checkout_payment_url(true))
);
} else if (version_compare(WOOCOMMERCE_VERSION, '2.0.0', '>=')) {
return array(
'result' => 'success',
'redirect' => add_query_arg(
'order',
$order->get_id(),
add_query_arg('key', $orderKey, $order->get_checkout_payment_url(true))
)
);
} else {
return array(
'result' => 'success',
'redirect' => add_query_arg(
'order',
$order->get_id(),
add_query_arg('key', $orderKey, get_permalink(get_option('woocommerce_pay_page_id')))
)
);
}
$order = wc_get_order($order_id);
}
/**
* Check for valid BillDesk server callback
**/
function check_billdesk_response()
{
$log = WooBillDeskLogger::defaultLogger();
global $woocommerce;
$error = "";
$success = false;
$billdeskPaymentId = null;
$wooorderid = (isset($_POST['wooorderid'])) ? $_POST['wooorderid'] : null;
error_log("Inside check_billdesk_response $wooorderid : " . $wooorderid . PHP_EOL, 0);
$amount = $woocommerce->cart->total;
error_log("Inside check_billdesk_response $amount : " . $amount . PHP_EOL, 0);
$log->debug("Found woocommerce orderid: $wooorderid");
$log->debug("Found order amount : $amount");
$log->debug("Found wooorderid: $wooorderid");
$sessionOrderId = $woocommerce->session->get(self::SESSION_KEY);
$log->debug("Found orderid in session: $sessionOrderId");
/* if (!$wooorderid) {
wp_redirect(wc_get_checkout_url());
exit;
} */
$txcode = (isset($_POST['txcode'])) ? $_POST['txcode'] : null;
$logger = WooBillDeskLogger::logger("Transaction_Responce");
$logger->debug("TXCODE : $txcode");
$encrypted_response = (isset($_POST['encrypted_response'])) ? $_POST['encrypted_response'] : null;
$logger = WooBillDeskLogger::logger("encrypted_response");
$logger->debug("encrypted_response : $encrypted_response");
$transaction_response = (isset($_POST['transaction_response'])) ? $_POST['transaction_response'] : null;
if ($encrypted_response != null){
$logger->debug("@@@@@@@@@@@@ Encrypted_response @@@@@@@@@@@@@@@@@@@@@@@@:");
$secret = $this->getSetting('merchant_key');
$client_id = $this->getSetting('client_id');
$client = new JWEHS256Helper($secret, $client_id);
$jws = $client->verifyAndDecrypt($encrypted_response);
$txn = json_decode($jws);
$logger->debug("Encrypted_response :" . json_encode($txn));
$bdorderid = $txn->additional_info->additional_info1;
$logger->debug("Encrypted_response :" . json_encode($txn));
$order = new WC_Order($sessionOrderId);
// $this->updateOrder($order, $success, $error, null);
$this->updateOrder($order, $success, $error, null, $txn);
}
else if ($transaction_response == null && $txcode === "111") {
$success = false;
$error = 'Payment was cancelled by the user.';
// Need to be relooked at.
$order = new WC_Order($sessionOrderId);
$this->updateOrder($order, $success, $error, null);
} else if ($transaction_response != null) {
$secret = $this->getSetting('merchant_key');
$client_id = $this->getSetting('client_id');
$client = new JWEHS256Helper($secret, $client_id);
$jws = $client->verifyAndDecrypt($transaction_response);
$txn = json_decode($jws);
$logger->debug("Transaction response :" . json_encode($txn));
$bdorderid = $txn->additional_info->additional_info1;
$order = new WC_Order($bdorderid);
if ($order->needs_payment() === false) {
$this->redirectUser($order);
}
error_log("Inside check_billdesk_response $bdorderid : " . $bdorderid . PHP_EOL, 0);
$logger->debug("bdorderid : $bdorderid");
error_log("Inside check_billdesk_response $txn->amount : " . $txn->amount . PHP_EOL, 0);
$logger->debug("txn->amount : $txn->amount");
if( $txn->amount >= $amount )
{
$order->add_order_note("BillDesk order Id <br/>order Id: $sessionOrderId");
$billdeskPaymentId = $txn->transactionid;
$order->add_order_note("BillDesk Transaction Id <br/>BillDesk Id: $billdeskPaymentId");
$logger->debug("transactionid : $txn->transactionid . $billdeskPaymentId");
if ($txn->auth_status == '0399') {
$logger->debug("failure_reason : $txn->transaction_error_desc");
$success = false;
$error = "Payment failed! Error code: " . $txn->transaction_error_code . " error: " . $txn->transaction_error_desc;
} else if ($txn->auth_status === '0300') {
$success = true;
} else if ($txcode == '111') {
$success = false;
$error = 'Customer cancelled the payment';
} else if ($txn->auth_status == '0002') {
$success = false;
$error = "Pending Payment, reff code: " . $txn->transaction_error_code . " error: " . $txn->transaction_error_desc;
}else if ($_POST[self::BILLDESK_WC_FORM_SUBMIT] == 1) {
$success = false;
$error = 'Customer cancelled the payment';
}
$this->handleErrorCase($order);
$logger->debug("check error response : $error");
$this->updateOrder($order, $success, $error, $billdeskPaymentId, $txn);
$this->thankyou_page( $bdorderid );
}
else {
$error = "Mismatch between Purchase Order and Amount Causes Receiving Transaction Error.";
$success = false;
$logger->debug("ERROR : Mismatch between Purchase Order and Amount Causes Receiving Transaction Error");
<<<EOT
<div class="woocommerce-notices-wrapper">
<ul class="woocommerce-error" role="alert">
<li> Mismatch between Purchase Order and Amount Causes Receiving Transaction Error </li>
</ul>
</div>
EOT;
}
} else {
$error = "Order failed. Please contact the support if problem persists.";
$success = false;
}
if ($success == false) {
$checkout_url = wc_get_checkout_url();
if($bdorderid == NULL){
$bdorderid = $sessionOrderId;
}
$checkout_url = add_query_arg('order_id', $bdorderid, $checkout_url);
wp_redirect($checkout_url);
exit;
}
if ($success == true) {
$this->redirectUser($order);
}
}
/**
* Modifies existing thankyou_page
*
* @var $billdeskPaymentId -> Process billdeskPaymentId
*/
public function thankyou_page($billdeskPaymentId)
{
global $table_prefix, $wpdb;
$tblname = 'woo_bldsk_order';
$wp_order_table = $table_prefix . "$tblname ";
$query = $wpdb->prepare(
"SELECT *
FROM $wp_order_table
WHERE order_id= %s ORDER BY id DESC LIMIT 1",
$billdeskPaymentId
);
$result = $wpdb->get_results($query);
$log = WooBillDeskLogger::logger("order_" . $billdeskPaymentId);
$log->info("Query results count: " . count($result) . " records: " . json_encode($result));
if (count($result) <= 0) {
$log->error("Unable to find payment details against order id: $billdeskPaymentId");
return;
}
$txn = json_decode(($result[0])->transaction_data);
$current_timestamp = strtotime($txn->transaction_date);
$date = date("d-m-Y ", $current_timestamp);
echo '<ul class="woocommerce-order-overview woocommerce-thankyou-order-details order_details" style="margin-top:0">
<li class="woocommerce-order-overview__order order">
Transaction ID: <strong> ' . $txn->transactionid . ' </strong>
</li>
<li class="woocommerce-order-overview__order order">
Transaction Date: <strong> ' . $date . ' </strong>
</li>
</ul>';
}
/**
* redirect user to return_url with order
* @param & $order
*/
protected function redirectUser($order)
{
$redirectUrl = $this->get_return_url($order);
wp_redirect($redirectUrl);
exit;
}
/**
* handles Error case
*
* @var $orderId -> Process Order ID
*
*/
protected function getErrorMessage($orderId)
{
if ($orderId !== null) {
$message = 'An error occured while processing this payment';
}
if (isset($_POST['error']) === true) {
$error = $_POST['error'];
$description = htmlentities($error['description']);
$code = htmlentities($error['code']);
$message = 'An error occured. Description : ' . $description . '. Code : ' . $code;
if (isset($error['field']) === true) {
$fieldError = htmlentities($error['field']);
$message .= 'Field : ' . $fieldError;
}
} else {
$message = 'An error occured. Please contact administrator for assistance';
}
return $message;
}
/**
* Modifies existing order and handles success case
*
* @param $success, & $order
*/
public function updateOrder(&$order, $success, $errorMessage, $billdeskPaymentId, $transaction_data = null)
{
$logger = WooBillDeskLogger::defaultLogger();
$logger->debug("Upadte order error response : $errorMessage");
global $woocommerce, $table_prefix, $wpdb;
$woo_order = $order->get_order_number();
$tblname = 'woo_bldsk_order';
$wp_order_table = $table_prefix . "$tblname ";
$trans_data = json_encode($transaction_data);
$wpdb->query("INSERT INTO $wp_order_table (transaction_data,order_id) VALUES('$trans_data','$woo_order')");
if (($success === true) and ($order->needs_payment() === true)) {
$this->msg['message'] = $this->getCustomOrdercreationMessage() . " Order Id: $woo_order";
$this->msg['class'] = 'success';
$order->payment_complete($billdeskPaymentId);
$order->add_order_note("BillDesk payment successful <br/>BillDesk Id: $billdeskPaymentId");
if (isset($woocommerce->cart) === true) {
$woocommerce->cart->empty_cart();
}
} else {
$this->msg['class'] = 'error';
$this->msg['message'] = $errorMessage;
if ($billdeskPaymentId) {
$order->add_order_note("Payment Failed. Please check Billdesk Dashboard. <br/> BillDesk Id: $billdeskPaymentId");
}
$order->add_order_note("Transaction Failed: $errorMessage<br/>");
$order->update_status('failed');
}
}
protected function handleErrorCase($woo_order)
{
$this->msg['class'] = 'error';
$this->msg['message'] = $this->getErrorMessage($woo_order);
$logger = WooBillDeskLogger::defaultLogger();
$logger->debug("Handle Error : $this->msg['message']");
}
}
/**
* Add the Gateway to WooCommerce
**/
function woocommerce_add_billdesk_gateway($methods)
{
$methods[] = 'WC_Billdesk';
return $methods;
}
add_filter('woocommerce_payment_gateways', 'woocommerce_add_billdesk_gateway');
}
function admin_enqueue()
{
wp_enqueue_script('woo-admin-config', plugin_dir_url(__FILE__) . 'includes/configue.js');
}
add_action('admin_enqueue_scripts', 'admin_enqueue');
function add_woo_id_to_script($tag, $handle, $src)
{
if ('billdeskwoo-module' === $handle) {
$tag = '<script type="module" src="' . $src . '"></script>';
}
if ('billdeskwoo-nomodule' === $handle) {
$tag = '<script nomodule="" src="' . $src . '"></script>';
}
return $tag;
}
add_filter('script_loader_tag', 'add_woo_id_to_script', 10, 3);