File: /home/madaktos/public_html/wp-content/plugins/kamanlend-woocommerce/kamanlend-payment.php
<?php
/*
* Plugin Name: کمان لند (درگاه پرداخت اعتباری)
* Plugin URI: https://kamanlend.ir
* Description: <b>درگاه پرداخت آنلاین کمان لند، برای فروشگاه ساز ووکامرس وردپرس</b>
* Version: 1.0
* Author: کمان لند
* Author URI: https://kamanlend.ir
* Text Domain: kamanlend-payment-for-woocommerce
* Domain Path: /languages
*/
add_action('plugins_loaded', function() {
load_plugin_textdomain('kamanlend-payment-for-woocommerce', false, basename(dirname(__FILE__)) . '/languages');
if (!class_exists('WC_Payment_Gateway')) return;
class WC_kamanlend extends WC_Payment_Gateway
{
public function __construct()
{
$this->id = 'kamanlend';
$this->plugin_name = __('Kamanlend Online Payment Method for WooCommerce', 'kamanlend-payment-for-woocommerce');
$this->method_title = __('Kamanlend Online Payment Gateway', 'kamanlend-payment-for-woocommerce');
$this->icon = plugin_dir_url(__FILE__) . 'images/logo.png';
$this->has_fields = false;
$this->init_form_fields();
$this->init_settings();
$this->title = __('Kamanlend Online Payment Gateway', 'kamanlend-payment-for-woocommerce');
$this->description = __('Pay by Kamanlend Online Payment Gateway', 'kamanlend-payment-for-woocommerce');
$this->terminal_code = $this->settings['terminal_code'];
$this->terminal_secret = $this->settings['terminal_secret'];
$this->show_loanstatus = $this->settings['show_loanstatus'] === 'yes';
$this->gateway_url = $this->settings['gateway_url'];
add_action('woocommerce_api_' . strtolower(get_class($this)), array($this, 'check_kamanlend_response'));
add_action('valid-kamanlend-request', array($this, 'successful_request'));
add_action('woocommerce_update_options_payment_gateways_kamanlend', array($this, 'process_admin_options'));
add_action('woocommerce_receipt_kamanlend', array($this, 'receipt_page'));
}
function init_form_fields()
{
$this->form_fields = array(
'enabled' => array(
'title' => __('Enable / Disable', 'kamanlend-payment-for-woocommerce'),
'type' => 'checkbox',
'label' => __('Enable or Disable This Payment Mehod', 'kamanlend-payment-for-woocommerce'),
'default' => 'yes'
),
'gateway_url' => array(
'title' => __('Kamanlend Online Gateway URL', 'kamanlend-payment-for-woocommerce'),
'type' => 'text',
'description' => __('Enter Kamanlend Online Gateway URL', 'kamanlend-payment-for-woocommerce'),
'placeholder' => 'https://gateway.kamanlend.ir',
'default' => 'https://gateway.kamanlend.ir'
),
'terminal_code' => array(
'title' => __('Kamanlend Online Payment Terminal Code', 'kamanlend-payment-for-woocommerce'),
'type' => 'text',
'description' => __('Enter Kamanlend Online Payment Terminal Code', 'kamanlend-payment-for-woocommerce')
),
'terminal_secret' => array(
'title' => __('Kamanlend Online Payment Terminal Secret', 'kamanlend-payment-for-woocommerce'),
'type' => 'text',
'description' => __('Enter Kamanlend Online Payment Terminal Secret', 'kamanlend-payment-for-woocommerce')
),
'show_loanstatus' => array(
'title' => __('Show Payment Status in Orders', 'kamanlend-payment-for-woocommerce'),
'type' => 'checkbox',
'default' => 'yes',
'description' => __('Show Payment Status in WooCommerce Orders Table', 'kamanlend-payment-for-woocommerce')
),
);
}
public function admin_options()
{
echo '<p style="font-size: 11pt; font-weight: bold; border-bottom: 3px dashed black; padding: 10px 5px">'.__('Kamanlend Online Payment Gateway', 'kamanlend-payment-for-woocommerce').'</p>';
echo '<table class="form-table">';
$this->generate_settings_html();
echo '</table>';
}
function payment_fields()
{
if (isset($_GET['pay_for_order']) && $_GET['pay_for_order'] == 'true') {
echo '<style type="text/css" media="screen">.payment_box.payment_method_kamanlend{visibility:hidden}</style>';
} else {
if ($this->description) echo esc_html($this->description);
?><fieldset id="kamanlend-cc-form" class='wc-kamanlend-form wc-payment-form'>
<p class="form-row form-row-wide validate-required">
<label for="kamanlend-mellicode"><?php _e('National (Melli) Code', 'kamanlend-payment-for-woocommerce'); ?> <span class="required">*</span></label>
<input id="kamanlend-mellicode" class="input-text wc-kamanlend-form-mellicode" type="text" maxlength="10" name="kamanlend-mellicode" required />
</p>
<div class="clear"></div>
</fieldset>
<?php
}
}
function process_payment($order_id)
{
$order = new WC_Order($order_id);
return array('result' => 'success', 'redirect' => $order->get_checkout_payment_url(true));
}
function receipt_page($order_id)
{
try
{
$order_time = time();
$saleItems = array();
$order = new WC_Order($order_id);
$order_currency_rate = get_woocommerce_currency() == 'IRR' ? 1 : 10;
$order_total = intval(ceil($order->get_total() * $order_currency_rate));
$order_items = $order->get_items();
foreach ($order_items as $item) {
$p = $order->get_product_from_item($item);
// $p->get_title()
$pTotal = intval($p->get_price() * $order_currency_rate * $item['qty']);
$order_total -= $pTotal;
$saleItems[] = array('code' => strval($p->get_sku()), 'title' => $item['name'], 'quantity' => $item['qty'], 'totalAmountRial' => $pTotal);
}
if ($order_total > 0) {
$saleItems[] = array('code' => '0', 'title' => __('Customer Service (Tax, Shipping and others)', 'kamanlend-payment-for-woocommerce'), 'count' => 1, 'totalAmountRial' => $order_total);
}
$redirectionUrl = get_option('woocommerce_myaccount_orders_endpoint', 'orders');
$redirectionUrl = wc_get_endpoint_url('orders', '', get_permalink(get_option('woocommerce_myaccount_page_id')));
if (!$redirectionUrl || get_current_user_id() == 0) {
$redirectionUrl = $this->get_return_url($order);
}
$ch = curl_init($url = $this->gateway_url . '/api/Gateway/RegisterPayment');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post = array(
'terminalCode' => $this->terminal_code,
'terminalSecret' => $this->terminal_secret,
'customerNationalCode' => get_post_meta($order_id, 'kamanlend_nationalcode', true),
'shoppingCardCode' => strval($order_time),
'stateChangeCallbackUrl' => add_query_arg(array('wc-api' => get_class($this), 'order_id' => $order_id), get_site_url().'/'),
'redirectionUrl' => $redirectionUrl,
'saleItems' => $saleItems
)));
curl_setopt($ch, CURLOPT_HTTPHEADER, $h = array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
$result = json_decode($response);
if (isset($result->success) && $result->success)
{
update_post_meta($order_id, 'kamanlend_order_time', $order_time);
update_post_meta($order_id, 'kamanlend_request', $result);
update_post_meta($order_id, 'kamanlend_token', $result->result->token);
update_post_meta($order_id, 'kamanlend_gatewayurl', $result->result->gatewayUrl);
echo '<p>'.__('thank you for your order. you are redirecting to Kamanlend online gateway. please wait', 'kamanlend-payment-for-woocommerce').'</p>';
echo '<a class="kamanlend_btn btn button" href="'.esc_url($result->result->gatewayUrl).'"> '.__('Pay', 'kamanlend-payment-for-woocommerce').' </a>';
echo '<script> document.location="'.esc_url($result->result->gatewayUrl).'" </script>';
@header('location: ' . $result->result->gatewayUrl);
}
elseif (isset($result->messages) && is_array($result->messages))
{
$msg = array();
foreach ($result->messages as $message) {
$msg[] = $message->message;
}
throw new exception(implode(' - ', $msg));
}
elseif ($error)
{
throw new exception($error);
}
else
{
throw new exception(__('UnExpected Error', 'kamanlend-payment-for-woocommerce'));
}
}
catch (exception $e)
{
$order->add_order_note(__('Erorr', 'kamanlend-payment-for-woocommerce') . ': ' . $e->getMessage());
echo '<p><font color="red">'.__('Erorr', 'kamanlend-payment-for-woocommerce').': '.esc_html($e->getMessage()).'</font></p>';
}
}
function check_kamanlend_response()
{
try
{
if (isset($_GET['order_id']))
{
$order_id = sanitize_text_field($_GET['order_id']);
$order = new WC_Order($order_id);
if (!($order && is_object($order)))
{
$message = __('Error : Order Not Exists!', 'kamanlend-payment-for-woocommerce');
throw new exception($message);
}
$ch = curl_init($url = $this->gateway_url . '/api/Gateway/GetPaymentState');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post = array(
'terminalCode' => $this->terminal_code,
'terminalSecret' => $this->terminal_secret,
'customerNationalCode' => get_post_meta($order_id, 'kamanlend_nationalcode', true),
'token' => get_post_meta($order_id, 'kamanlend_token', true),
)));
curl_setopt($ch, CURLOPT_HTTPHEADER, $h = array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
$result = json_decode($response);
if (isset($result->success) && $result->success)
{
if ($result->result->saleRequestState == get_post_meta($order_id, 'kamanlend_sale_status', true))
{
exit(500);
}
update_post_meta($order_id, 'kamanlend_result', $result);
update_post_meta($order_id, 'kamanlend_sale_status', $result->result->saleRequestState);
update_post_meta($order_id, 'kamanlend_sale_status_title', $result->result->saleRequestStateTitle);
$message = sprintf(__("New Loan Status : %s", 'kamanlend-payment-for-woocommerce'), $result->result->saleRequestStateTitle);
$order->add_order_note($message, true);
if ($result->result->saleRequestState == 'PaymentCompleted')
{
$order_currency_rate = get_woocommerce_currency() == 'IRR' ? 1 : 10;
$order_total = intval(ceil($order->get_total() * $order_currency_rate));
$message = sprintf(__("Payment Completed. OrderID : %s", 'kamanlend-payment-for-woocommerce'), $order_id);
$order->payment_complete();
$order->add_order_note($message, true);
}
exit(200);
}
else
{
$msg = array();
foreach ($result->messages as $message) {
$msg[] = $message->message;
}
$order->add_order_note($message);
throw new exception(implode(' - ', $msg));
}
}
else
{
$message = __('System (Permission) Error!', 'kamanlend-payment-for-woocommerce');
throw new exception($message);
}
}
catch (exception $e)
{
echo esc_html($e->getMessage());
exit(500);
}
}
}
add_action('woocommerce_checkout_process', function() {
$do = false;
$chosen_gateway = $mellicode = '';
if (isset($_POST['kamanlend-mellicode'])) {
$do = true;
$mellicode = $_POST['kamanlend-mellicode'];
$chosen_gateway = $_POST['payment_method'];
}
elseif (isset($_POST['post_data'])) {
parse_str($_POST['post_data'],$post_data);
if (isset($post_data['kamanlend-mellicode'])) {
$do = true;
$mellicode = $post_data['kamanlend-mellicode'];
$chosen_gateway = $post_data['payment_method'];
}
}
if ($do === true && $chosen_gateway == 'kamanlend') {
if (!validateMelliCode($mellicode)) {
wc_add_notice(__("<b>National (Melli) Code</b> : Please Enter valid National (Melli) Code", 'kamanlend-payment-for-woocommerce'), 'error');
}
}
}, 666);
add_action('woocommerce_checkout_update_order_meta', function($order_id) {
if (isset($_POST['kamanlend-mellicode'])) {
update_post_meta($order_id, 'kamanlend_nationalcode', sanitize_text_field($_POST['kamanlend-mellicode']));
}
}, 666);
add_filter('woocommerce_payment_gateways', function ($methods) {
array_unshift($methods , 'WC_kamanlend');
return $methods;
}, PHP_INT_MAX);
add_filter('plugin_action_links_' . plugin_basename(__FILE__), function ($links) {
return array_merge(array('settings' => '<a href="'.admin_url('admin.php?page=wc-settings&tab=checkout§ion=kamanlend').'">'.__('Settings', 'kamanlend-payment-for-woocommerce').'</a>'), $links);
});
add_filter('manage_shop_order_posts_columns', function($columns) {
$x = new WC_kamanlend;
if ($x->show_loanstatus) {
$columns['kamanlend_sale_status_title'] = __('Payment Status', 'kamanlend-payment-for-woocommerce');
}
return $columns;
}, 666);
add_action('manage_shop_order_posts_custom_column', function($column, $order_id) {
if ($column == 'kamanlend_sale_status_title') {
if ($loan_status = get_post_meta($order_id, 'kamanlend_sale_status_title', true)) {
echo $loan_status;
} elseif (get_post_meta($order_id, 'kamanlend_gatewayurl', true)) {
echo __('PaymentInitialized', 'kamanlend-payment-for-woocommerce');
} else {
echo '';
}
}
}, 666, 2);
if (!function_exists('validateMelliCode')) {
function validateMelliCode($value) {
if (!preg_match('/^[0-9]{10}$/',$value)) {
return (bool) false;
}
for ($i=0;$i<10;$i++) {
if (preg_match('/^'.$i.'{10}$/',$value)) {
return (bool) false;
}
}
for ($i=0,$sum=0;$i<9;$i++) {
$sum+=((10-$i)*intval(substr($value, $i,1)));
}
return true;
$ret=$sum%11;
$parity=intval(substr($value, 9,1));
if (($ret<2 && $ret==$parity) || ($ret>=2 && $ret==11-$parity)) {
return (bool) true;
}
return (bool) false;
}
}
}, 666);
?>