File: /storage/v4513/ivenusin/public_html/wp-content/themes/ivenus/inc/cashify-actions.php
<?php
require_once( THEME_DIR. '/inc/phpseclib/Crypt/RSA.php');
require_once( THEME_DIR. '/inc/phpseclib/Crypt/Random.php');
require_once( THEME_DIR. '/inc/phpseclib/Math/BigInteger.php');
require_once( THEME_DIR. '/inc/phpseclib/Crypt/Hash.php');
use phpseclib\Crypt\RSA;
/* Cashify Setting Field */
// REMEMBER TO CREATE TABLE IN DATABASE
add_action('admin_init', 'ivenus_general_section');
function ivenus_general_section() {
add_settings_section( 'cashify_settings', 'Cashify Settings', 'cashify_settings_callback', 'general' );
add_settings_field( 'cashify_mode','Enable Cashify','ivenus_checkbox_callback','general','cashify_settings',array('cashify_mode') );
register_setting('general','cashify_mode', 'esc_attr');
}
function cashify_settings_callback() {
echo '<p>This options is used to enable/disable Cashify widget feature.</p>';
}
function ivenus_checkbox_callback($args) {
$option = get_option($args[0]);
echo '<input type="checkbox" id="'. $args[0] .'" name="'. $args[0] .'" value="1"' . checked( 1, $option, false ) .' />';
}
/* function cashify_modify_menu($items, $args) {
$cashify_mode = get_option('cashify_mode');
if( $args->theme_location == 'header' && $cashify_mode === "1" ){
$items .= '<li class="cashify-exchange menu-item menu-item-type-post_type menu-item-object-page">'
. '<a href="'.home_url( '/' ).'exchange/" class="menu-image-title-after">'
. '<span class="menu-image-title-after menu-image-title">Exchange</span></a></li>';
}
return $items;
}
add_filter('wp_nav_menu_items', 'cashify_modify_menu', 10, 2); */
/* Cashify Admin Page */
if(!class_exists('WP_List_Table')) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
if(class_exists('WP_List_Table')):
class Cashify_Table extends WP_List_Table
{
private $order;
private $orderby;
private $posts_per_page = 25;
public function __construct()
{
parent :: __construct(array(
'singular' => "ivenus_cashify",
'plural' => "ivenus_cashify",
'ajax' => false
));
$this->set_order();
$this->set_orderby();
$this->prepare_items();
$this->display();
}
private function get_sql_results()
{
global $wpdb;
$args = array('id', 'user_id', 'pid', 'pn', 'amount', 'ref_code', 'service_id', 'r_id', 'service_status', 'order_id', 'date_created', 'last_modified');
$sql_select = implode(', ', $args);
$sql_results = $wpdb->get_results("SELECT " . $sql_select . " FROM " . $wpdb->prefix . "ivenus_cashify ORDER BY $this->orderby $this->order ");
return $sql_results;
}
public function set_order()
{
$order = 'DESC';
if (isset($_GET['order']) AND $_GET['order'])
$order = $_GET['order'];
$this->order = esc_sql($order);
}
public function set_orderby()
{
$orderby = 'id';
if (isset($_GET['orderby']) AND $_GET['orderby'])
$orderby = $_GET['orderby'];
$this->orderby = esc_sql($orderby);
}
/**
* @see WP_List_Table::no_items()
*/
public function no_items()
{
_e('No record found.');
}
/**
* @see WP_List_Table::get_views()
*/
public function get_views()
{
return array();
}
/**
* @see WP_List_Table::get_columns()
*/
public function get_columns()
{
$columns = array(
'id' => __('ID'),
'user_id' => __('User ID'),
'pn' => __('Product Name'),
'amount' => __('Amount'),
'ref_code' => __('Ref Code'),
'service_id' => __('Service Number'),
'service_status' => __('Service Status'),
'order_id' => __('Order ID'),
'date_created' => __('Created on')
);
return $columns;
}
/**
* @see WP_List_Table::get_sortable_columns()
*/
public function get_sortable_columns()
{
$sortable = array(
'id' => array('id', true),
'user_id' => array('user_id', true),
'pn' => array('pn', true),
'amount' => array('amount', true),
'service_status' => array('service_status', true),
'date_created' => array('date_created', true),
);
return $sortable;
}
/**
* Prepare data for display
* @see WP_List_Table::prepare_items()
*/
public function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
$this->_column_headers = array(
$columns,
$hidden,
$sortable
);
// SQL results
$posts = $this->get_sql_results();
empty($posts) AND $posts = array();
# >>>> Pagination
$per_page = $this->posts_per_page;
$current_page = $this->get_pagenum();
$total_items = count($posts);
$this->set_pagination_args(array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil($total_items / $per_page)
));
$last_post = $current_page * $per_page;
$first_post = $last_post - $per_page + 1;
$last_post > $total_items AND $last_post = $total_items;
// Setup the range of keys/indizes that contain
// the posts on the currently displayed page(d).
// Flip keys with values as the range outputs the range in the values.
$range = array_flip(range($first_post - 1, $last_post - 1, 1));
// Filter out the posts we're not displaying on the current page.
$posts_array = array_intersect_key($posts, $range);
# <<<< Pagination
// Prepare the data
/* $permalink = __('Edit:');
foreach ($posts_array as $key => $post) {
$link = get_edit_post_link($post->ID);
$no_title = __('No title set');
$title = !$post->post_title ? "<em>{$no_title}</em>" : $post->post_title;
$posts[$key]->post_title = "<a title='{$permalink} {$title}' href='{$link}'>{$title}</a>";
} */
$this->items = $posts_array;
}
/**
* A single column
*/
public function column_default($item, $column_name)
{
return $item->$column_name;
}
/**
* Override of table nav to avoid breaking with bulk actions & according nonce field
*/
public function display_tablenav($which)
{
?>
<div class="tablenav <?php echo esc_attr($which); ?>">
<!--
<div class="alignleft actions">
<?php # $this->bulk_actions( $which ); ?>
</div>
-->
<?php
$this->extra_tablenav($which);
$this->pagination($which);
?>
<br class="clear" />
</div>
<?php
}
/**
* Disables the views for 'side' context as there's not enough free space in the UI
* Only displays them on screen/browser refresh. Else we'd have to do this via an AJAX DB update.
*
* @see WP_List_Table::extra_tablenav()
*/
public function extra_tablenav($which)
{
global $wp_meta_boxes;
$views = $this->get_views();
if (empty($views)) return;
$this->views();
}
}
endif;
add_action( 'admin_menu', 'cashify_menu_page' );
function cashify_menu_page() {
$cashify_mode = get_option('cashify_mode');
if( $cashify_mode === "1" ){
add_menu_page(
'Cashify Entry',
'Cashify Entry',
'manage_options',
'cashify-entry',
'cashify_page_content',
'dashicons-welcome-view-site',
100
);
}
}
function cashify_page_content(){
echo '<div class="wrap"><h2>'. __('Cashify Exchange Data') .'</h2>';
$ftList = new Cashify_Table();
echo '</div>';
}
// initiate CURL on order success
// add_action('woocommerce_thankyou', 'ivenus_cashify_exchange', 10, 1);
add_action('woocommerce_order_status_changed', 'ivenus_cashify_exchange', 10, 3);
function ivenus_cashify_exchange($order_id,$old_status,$new_status) {
// Only when admin changes status to completed code needs to be executed
if ( $new_status !== 'completed')
return;
// 1. Allow code execution only once
if( ! get_post_meta( $order_id, '_thankyou_action_done', true ) ) {
// 2. Check if product category is iPhone
$order = wc_get_order( $order_id );
$cat_in_order = false;
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
if ( has_term( 'iphone', 'product_cat', $product_id ) ) {
$cat_in_order = true;
break;
}
}
if ( $cat_in_order ) {
// 3. Get current user ID
$current_user_id = $order->get_customer_id();
// 4. Check IF user ID requested any quote from Cashify Exchange
global $wpdb;
$exchange_result = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}ivenus_cashify WHERE user_id = {$current_user_id} AND service_id IS NULL order by id desc limit 1", OBJECT );
if ( !empty($exchange_result) ) {
// 5. Generate secure token (key|soure|epoch)
$rsa = new RSA();
$key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj6g5L2nqW7SdGfevQ0DDfuV7t2X9z7ZIlv4dP2PPB9xRnTfm0D23d2Mxpm6Ga+IK4vwPiJw3KM7gf7jDCNd3ejWClsQWd17jKuKxu+CS/n0/jqTc+07pXYpF9w01PBM1Zh8nn2+J/RhGy6S3dG+Arcv4Y7/x3R3VVNJg9OtTcqmwDaX/+1AWkOOiHWXNSPMmmsQMGzWZ4K09JfWdpRJXzNTSwqm8yud6dcuuKoVhQIlCFCVwkWMFTikbaGUbPWIMnsaSke4RKPYru7wjjM6XbgjvKYnRzJ4WKPA/LltzEZ2ezaY7TY+cNEN2omhAr43D8nsd6m7jJZ3RKkYguEY+twIDAQAB';
$rsa->loadKey($key);
$plaintext = '434166a2ab8a18d4c557fec968ac8e32' . '|' . 'venusonline' . '|' . time();
$rsa->setEncryptionMode($rsa::ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);
$token = base64_encode($ciphertext);
/* $ciphertext = base64_encode($ciphertext);
$private_key = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC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a63eJgzAG//S4cKa0OFxHzS5CjxZPr7m39DxuxGp0gy+enpU3PFBp2pV62LWCN8GGKep2mR6mVfRBf7Tu7JzSRFNctgqt8PRwAN3LKLPd7o9AzrCDvOQ1H+jH4nJ+Q/kH6/MVo3+k1OQzLPfyjOrOsFZH/uQKBgHmAk3UEa5+mL91m/1Lb8dMOPeelTX9rSOC2c00TFDu09w9QOKgYGt81tkZTxY+2S/add1RNx7UxMHecwWqvsMsNN10yDt3C/b3PsPE1AtLjGia8UOZVXKhKvyZ0kwUVEyRq25UekpcANp/48+KjN8zlaqk7LIPUpaHOmo2A2g6BAoGAIghrOKzJmRF+UkvpHTQkHXnhSxnuhgjKiySbXiYHzp2rLcwv7y1nlCzkUWLRIE14/LBA0D8RwWgydqWzzthdnolSLu3tHlTpUbKsonYgS1H9PAoAaaJNVEFbkcaZaBSJC1hh7/OlSi2O6iTAwiNc1tGvutSoQReMwbnFMn5XZCo=';
$rsa->loadKey($private_key);
echo '<br/>Decrypted<br/>';
$ciphertext = base64_decode($ciphertext);
var_dump($rsa->decrypt($ciphertext)); */
if($ciphertext) {
// 6. POST CURL Request
$postRequest = array(
"name" => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
"mobile" => $order->get_billing_phone(),
"email" => $order->get_billing_email(),
"address" => $order->get_billing_address_1() . ' ' . $order->get_billing_address_2(),
"pincode" => $order->get_billing_postcode(),
"refCode" => $exchange_result[0]->ref_code,
"partnerRef" => "ivenusTest",
"city" => $order->get_billing_city(),
"state" => $order->get_billing_state()
);
$postHeader = array(
"ACCESS-KEY: 434166a2ab8a18d4c557fec968ac8e32",
"SECURE-TOKEN: $token",
"Content-Type: application/json"
);
$cURLConnection = curl_init('https://lego.api.cashify.in/v1/widget/orders/create');
curl_setopt($cURLConnection, CURLOPT_POST, 1);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, json_encode(array("ordersList" => [$postRequest])));
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $postHeader);
$apiResponse = curl_exec($cURLConnection);
curl_close($cURLConnection);
// $apiResponse - available data from the API request
$jsonArrayResponse = json_decode($apiResponse);
// debug_to_console($apiResponse);
$order->add_order_note($apiResponse);
// 7. Update table with service number
if(property_exists($jsonArrayResponse, 'msg')) {
if($jsonArrayResponse->msg == 'success') {
if($jsonArrayResponse->res->orderList[0]->status == 1) {
$id = (int)$exchange_result[0]->id;
$update_result = $wpdb->update($wpdb->prefix.'ivenus_cashify', array( 'service_id' => $jsonArrayResponse->res->orderList[0]->serviceNumber, 'r_id' => $jsonArrayResponse->r_id, 'order_id' => $order_id), array('id' => $id));
// debug_to_console('Update Query: ' . $update_result);
if($update_result == 1) {
// 8. Display info message
$note = __("Cashify exchange request has been created successfully.");
$order->add_order_note( $note );
// echo '<div class="alert alert-info text-center">Cashify exchange request has been created successfully.</div>';
}
}
}
}
}
}
}
/*
// Flag the action as done (to avoid repetitions on reload for example)
$order->update_meta_data( '_thankyou_action_done', true );
$order->save(); */
}
}
function debug_to_console($output) {
echo "<script>console.log('Info: " . $output . "' );</script>";
}
/* After login redirect to exchange */
function login_redirect() {
$query = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
if ($query === 'exchange') {
wp_redirect(home_url('/') . 'exchange/');
}
}
add_filter('woocommerce_login_redirect', 'login_redirect', 1100, 2);
?>