<repo_name>loqtaApp/loqtaOrders<file_sep>/getProductByCustomerOrOrder.php
<?php

include 'slackWebHooks/settings.php';
$data = json_decode($data, true);

$ordersURL = "{$mainURLEndPoint}/orders.json";
$customersURL = "{$mainURLEndPoint}/customers/search.json?query=";

$palpayOauthKey = '83c9c662d05a81a4b58d009fe792e7e953e26a6b';

$currentTime = date("Y/m/d h:i");
$dateToVeirifyToken = date("d/m/y H");

$tokenToVeirify = md5($palpayOauthKey . $dateToVeirifyToken);

//die($tokenToVeirify);
//die(sha1(uniqid("palpay_operations", true)));

$token = $_GET['tt'];
$retriveKeyValue = ($_GET['idd']);
$actionKey = ($_GET['pay']);
$point_of_sale = ($_GET['pos']);
$payment_amount = ($_GET['amount']);
$orderFilterUnPaidOnlyStatus = ($_GET['unpaid']);
$payment_method = ($_GET['method']) ? $_GET['method'] : 'palpay';

$payment_currency = ($_GET['currency']) ? $_GET['currency'] : 'ILS';


define('PAY_ACTION', 1);
define('CANCEL_ACTION', 2);

define('PALPAY_PAID_TAG', 'PAID_PAL_PAY');
define('PALPAY_TAG', PALPAY_PAID_TAG . ', ' . strtoupper($payment_currency));

$palpay_note = '"';
$palpay_note .= 'تم دفع';
$palpay_note .= "($payment_amount)";
$palpay_note .= "بعملة ال";
$palpay_note .= "($payment_currency)";
$palpay_note .= 'بتاريخ ';
$palpay_note .= "($currentTime)";
$palpay_note .= '"';

$payment_inc_amount['palpay'] = 2;

define('PALPAY_ORDER_NOTE', $palpay_note);
define('PALPAY_ORDER_CANCEL_NOTE', ' تم إلغاء دفع هذا الطلب بواسطة بال بي');



$ordersFilter = "financial_status=pending&fulfillment_status=unshipped&name=";

$note_palpay_elements[] = array('name' => 'palpay_paid_date', 'value' => date("Y/m/d h:i"));
$note_palpay_elements[] = array('name' => 'palpay_pos', 'value' => $point_of_sale);
$note_palpay_elements[] = array('name' => 'payment_amount', 'value' => $payment_amount);
$note_palpay_elements[] = array('name' => 'payment_currency', 'value' => $payment_currency);


//operations
define('LOOK_FOR_CUSTOMER_VIA_CUSTOMER_ID', 1);
define('LOOK_FOR_ORDER_VIA_CUSTOMER_ID', 2);
define('LOOK_FOR_ORDER_VIA_ORDER_ID', 3);
define('PAY_ORDER_VIA_ORDER_ID', 4);
define('CANCEL_ORDER_VIA_ORDER_ID', 5);



$resultMessages = array();
$resultOperations = array();
$resultOrders = array();
$resultStatus = true;
$customerInformation = array();

if ($tokenToVeirify != $token) {
    $resultStatus = false;
    $resultMessages[] = 'Invalid Token, Or Expired Token';
}

if ($resultStatus) {

    function estimateOrderPriceInUSD($order) {
        $exRate = $order['total_price'] / $order['total_price_usd'];
        return $order["subtotal_price"] / $exRate;
    }

    function getOrdersByLink($link) {
        $request = new Request($link);
        $response = $request->execute();
        if (array_key_exists('orders', $response) && sizeof($response["orders"]) > 0) {
            return $response['orders'];
        } else {
            //no orders found
            return false;
        }
    }

    function filterOrders($order) {
        global $orderFilterUnPaidOnlyStatus;
        if ($orderFilterUnPaidOnlyStatus == true) {
            if (array_key_exists('tags', $order) && $order['tags'] != '') {
                if (strstr($order['tags'], PALPAY_PAID_TAG)) {
                    return false;
                } else {
                    return true;
                }
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    function getTransactionFees($price) {
        global $payment_inc_amount, $payment_method;
        return ceil(($payment_inc_amount[$payment_method] * $price) / 100);
    }

    function getTheFinalPriceWithTransactionFees($price) {
        return ceil(getTransactionFees($price) + $price);
    }

    function getPreparedOrderInformation($order) {
        global $payment_inc_amount, $payment_method;
        $preparedOrder['order_number'] = $order['order_number'];
        $preparedOrder["subtotal_price"] = getTheFinalPriceWithTransactionFees($order["subtotal_price"]);
        $preparedOrder["subtotal_price_usd"] = estimateOrderPriceInUSD($order);

        $itemTitles = '';
        $itemsSize = sizeof($order["line_items"]);
        $i = 0;
        foreach ($order["line_items"] as $lineItem) {
            $itemTitles .= $lineItem['title'] . ' - ' . $lineItem['price'] . ((($itemsSize - 1) == $i) ? '' : ',');
            $i++;
        }
        $itemTitles .= "+ Transfer Price (" . getTransactionFees($order["subtotal_price"]) . ")";
        $preparedOrder["line_items"] = $itemTitles;
        $preparedOrder["address"] = ($order['shipping_address']["address1"] != null) ? $order['shipping_address']["address1"] : $order['customer']["default_address"]["address1"];

        return $preparedOrder;
    }

    function updateOrderPalPay($requestedOrder, $postNoteData) {
        global $mainURLEndPoint;
        $shopifyParamsURL = $mainURLEndPoint . '/orders/' . $requestedOrder['id'] . ".json";
        $request = new Request($shopifyParamsURL);
        $request->setURL($shopifyParamsURL);
        $request->setHeaders(array(
            'Content-Type:application/json'
        ));
        $request->setData(json_encode($postNoteData));
        $request->setMethod('PUT');

        return $request->execute();
    }

    $numberOfDigits = strlen((string) $retriveKeyValue);
    if ($numberOfDigits < 8) {
        //get orders path
        $params = "?" . $ordersFilter . $retriveKeyValue;
        $requestedOrder = '';


        $orders = getOrdersByLink($ordersURL . $params);
        foreach ($orders as $order) {

            if ($order['order_number'] == $retriveKeyValue) {
                $requestedOrder = $order;
            }
        }
        if (!$orders || $requestedOrder == '' || !(filterOrders($requestedOrder))) {
            $resultOperations[] = array(LOOK_FOR_ORDER_VIA_ORDER_ID => false);
            $resultMessages[] = 'No orders found for "' . $retriveKeyValue . '"';
            $resultStatus = false;
        } else {

            $resultOperations[] = array(LOOK_FOR_ORDER_VIA_ORDER_ID => true);
            $resultMessages[] = 'Order found with number "' . $retriveKeyValue . '"';
            $customerInformation["first_name"] = $orders[0]['customer']["first_name"];
            $customerInformation["last_name"] = $orders[0]['customer']["last_name"];
            $customerInformation["phone"] = ($orders[0]['customer']["phone"] != null) ? $orders[0]['customer']["phone"] : $orders[0]['customer']["default_address"]["phone"];
            $preparedOrder = getPreparedOrderInformation($requestedOrder);
            $resultOrders = [$preparedOrder];

            if ($actionKey == PAY_ACTION) {

                $postNoteData['order']['id'] = $requestedOrder['id'];
                $postNoteData['order']['tags'] = (array_key_exists('tags', $requestedOrder) && $requestedOrder['tags'] != '') ? $requestedOrder['tags'] . ', ' . PALPAY_TAG : PALPAY_TAG;
                if (array_key_exists('note_attributes', $requestedOrder) && is_array($requestedOrder['note_attributes'])) {
                    $note_attributes = $requestedOrder['note_attributes'];
                    foreach ($note_palpay_elements as $note_palpay_element)
                        array_push($note_attributes, $note_palpay_element);
                } else {
                    $note_attributes = $note_palpay_elements;
                }
                $postNoteData ['order']['note_attributes'] = $note_attributes;
                $postNoteData ['order']['note'] = (array_key_exists('note', $requestedOrder) && $requestedOrder['note'] != '') ? $requestedOrder['note'] . ' ' . PALPAY_ORDER_NOTE : PALPAY_ORDER_NOTE;
                $shopifyResponse = updateOrderPalPay($requestedOrder, $postNoteData);

                if (array_key_exists('order', $shopifyResponse) && $shopifyResponse['order']['id']) {
                    $resultMessages[] = 'Order "' . $retriveKeyValue . '" was paid Successfully';
                    $resultOperations[] = array(PAY_ORDER_VIA_ORDER_ID => true);
                } else {
                    $resultMessages[] = 'Error in pay order "' . $retriveKeyValue . '"';
                    $resultOperations[] = array(PAY_ORDER_VIA_ORDER_ID => false);
                    $resultStatus = false;
                }
            }
            if ($actionKey == CANCEL_ACTION) {
                $tagsStr = str_replace(', ' . PALPAY_TAG, "", $requestedOrder['tags']);
                $tagsStr = str_replace(PALPAY_TAG, "", $tagsStr);


                $postNoteData['order']['tags'] = $tagsStr;
                $postNoteData['order']['note'] = $requestedOrder['note'] . ' ' . PALPAY_ORDER_CANCEL_NOTE;

                $note_attributes = $requestedOrder['note_attributes'];
                array_push($note_attributes, array('name' => 'palpay_cancel_date', 'value' => date("Y/m/d h:i")));
                $postNoteData['order']['note_attributes'] = $note_attributes;

                $shopifyResponse = updateOrderPalPay($requestedOrder, $postNoteData);
                if (array_key_exists('order', $shopifyResponse) && $shopifyResponse['order']['id']) {
                    $resultMessages[] = 'Order "' . $retriveKeyValue . '" was canceled Successfully';
                    $resultOperations[] = array(CANCEL_ORDER_VIA_ORDER_ID => true);
                } else {
                    $resultMessages[] = 'Error in cancel order "' . $retriveKeyValue . '"';
                    $resultOperations[] = array(CANCEL_ORDER_VIA_ORDER_ID => false);
                    $resultStatus = false;
                }
            }
        }
    } else {
        $email = $retriveKeyValue . '@loqta.ps';
        $requestedCustomer = '';

        //get customer path
        $customersURL = $customersURL . 'email:' . $email . ';fields=id,email,phone';
        $request = new Request($customersURL);
        $response = $request->execute();
        if (array_key_exists('customers', $response) && sizeof($response["customers"]) > 0) {
            $resultOperations[] = array(LOOK_FOR_CUSTOMER_VIA_CUSTOMER_ID => true);
            $customers = $response["customers"];
            foreach ($customers as $customer) {
                if ($customer['email'] == $email) {
                    $requestedCustomer = $customer;
                }
            }
            $customerID = $requestedCustomer["id"];
            $orders = getOrdersByLink($ordersURL . "?customer_id=" . $customerID . '&' . $ordersFilter);

            if (!$orders || $requestedCustomer == '') {
                $resultOperations[] = array(LOOK_FOR_ORDER_VIA_CUSTOMER_ID => false);

                $resultMessages[] = 'No orders found for customer "' . $customer['first_name'] . '"';
            } else {
                $resultOperations[] = array(LOOK_FOR_ORDER_VIA_CUSTOMER_ID => true);
                $preparedOrders = [];
                foreach ($orders as $order) {
                    if (filterOrders($order)) {
                        $preparedOrders[] = getPreparedOrderInformation($order);
                    }
                }

                $customerInformation["first_name"] = $orders[0]['customer']["first_name"];
                $customerInformation["last_name"] = $orders[0]['customer']["last_name"];
                $customerInformation["phone"] = ($orders[0]['customer']["phone"] != null) ? $orders[0]['customer']["phone"] : $orders[0]['customer']["default_address"]["phone"];

                $resultOrders = ($preparedOrders);
            }
        } else {
            $resultOperations[] = array(LOOK_FOR_CUSTOMER_VIA_CUSTOMER_ID => false);
            //no customer found
            $resultMessages[] = 'No customer name found for id "' . $retriveKeyValue . '"';
        }
    }
}
$result_of_operations = array(
    'orders' => $resultOrders,
    'customer' => $customerInformation,
    'operations' => $resultOperations,
    'status' => $resultStatus,
    'messages' => $resultMessages
);

die(json_encode($result_of_operations));
<file_sep>/firebase/nbproject/private/private.properties
index.file=index.php
url=http://localhost/firebase/
<file_sep>/slackWebHooks/request.php
<?php

class Request {

    protected $url;
    protected $headers = array();
    protected $data = array();
    protected $filePointer;
    protected $method = 'GET';
    protected $timeOut = 15;

    function __construct($url, $method = 'GET', $data = NULL) {
        $this->url = $url;
        $this->data = $data;
        $this->method = $method;
        $this->headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
        );
    }

    public function setURL($url) {
        $this->url = $url;
    }
    public function setData($data) {
        $this->data = $data;
    }
    public function setMethod($method) {
        $this->method = $method;
    }    
    public function putHeaders(&$ch) {
        $fp = fopen('php://temp/maxmemory:256000', 'w');
        if (!$fp) {
            die('could not open temp memory data');
        }
        fwrite($fp, $this->data);
        fseek($fp, 0);
        curl_setopt($ch, CURLOPT_PUT, 1);
        curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer
        curl_setopt($ch, CURLOPT_INFILESIZE, strlen($this->data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    }

    public function getHeaders(&$ch) {
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    }

    public function postHeaders(&$ch) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->data);
    }

    public function deleteHeaders(&$ch) {
        
    }

    public function setHeaders($headers) {
        $this->headers = $headers;
    }

    public function execute($arrayResponse = true) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);

        $methodHeaders = (strtolower($this->method) . 'Headers');
        $this->$methodHeaders($ch);

        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeOut);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        $xml_response = curl_exec($ch);
        curl_close($ch);
        return ($arrayResponse) ? json_decode($xml_response, true) : $xml_response;
    }

}
<file_sep>/firebase/index.php
<?php

header('Content-Type: application/json');

//initialize request  to create order with wehook


require __DIR__.'/vendor/autoload.php';

use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
use Kreait\Auth;
$data = json_decode(file_get_contents('php://input'),true);


$mainURL = "https://f3aa0d6659405ab34f9c0af85d0f2ef9:590b142f0e9922bd187703cd6729bae8@<EMAIL>.myshopify.com/admin/customers/".$data['customer']['id']."/metafields.json";

/***
 * initliaze request
 */
$headers = array(
	'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $mainURL);
curl_setopt($ch, CURLOPT_GET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);




$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/google-services.json');

$firebase = (new Factory)
    ->withServiceAccount($serviceAccount)
    ->create();

$auth = $firebase->getAuth();
try{
  $users = $auth->createUserWithEmailAndPassword($data['customer']['email'], $result['metafields']['value']);
  echo "true";
}catch(Exception $e){
  echo "fasle";
}




?>
<file_sep>/slackWebHooks/slackwebhook.php
<?php

define('NO_DEFAULT_HEADERS', true);
include 'settings.php';
//initialize request  to create order with wehook
//define the link for the slack (out Gaza or in Gaza)

$outGazaCarrier = 'CarrierMohammed';
date_default_timezone_set("Asia/Gaza");
$todayDate = date("Y/m/d h:i");
$orderStatus = '';
$orderNoteForShortLink = 'shortAdminLink';
$orderNoteShortLinkValue = '';
//////////////////slack

$channel = 'C6LB5HXD0';
$cancelledChannelID = 'C7WUEGNHG';
$text = '';
$fullfilledStatusReaction = ':racing_motorcycle:';
$paidStatusReaction = ':100:';
$cancelStatusReaction = ':x:';
$slackMSGTS = 'slack_message_id';
$token = base64_decode("<KEY>);
$tsMSG_ID = '';
$postMessageEndPoint = "https://slack.com/api/chat.postMessage";
$updatePostMessageEndPoint = "https://slack.com/api/chat.update";

//////////////////slack
//define the client source if possible 
//https://github.com/firebase/quickstart-js/tree/master/messaging

$data = json_decode($data, true);



/// Get all the order information 
$request = new Request($mainURLEndPoint . '/orders.json?ids=' . $data['id'] . '&status=any');
$response = $request->execute();
$order = $response['orders'][0];

//////////////////
$pushNotificationToken = '';
$pushNotificationTokenAttribute = 'PushNotificationToken';
$fcmEndPoint = "https://fcm.googleapis.com/fcm/send";
$webAPIKey = base64_decode('<KEY>');
$fullFillmentPushMSGTitle = ' تم خروج طلب رقم';
$fullFillmentPushMSGTitle .= $order['name'];
$fullFillmentPushMSGBody .= 'شكرا لتعاملك معنا';

$paidStatusPushMSGTitle = ' تم تأكيد إستلام طلب رقم';
$paidStatusPushMSGTitle .= $order['name'];
$paidStatusPushMSGBody = 'شكرا لتعاملك معنا';


$cancelPushMSGTitle = ' تم إلغاء طلب رقم';
$cancelPushMSGTitle .= $order['name'];
$cancelPushMSGBody .= 'شكرا لتعاملك معنا';
//////////////////
//
// check the order params
$notesArray = array();
foreach ($order['note_attributes'] as $note) {
    //push notification token 
    $notesArray[$note['name']] = $note['value'];

    if ($note['name'] == $pushNotificationTokenAttribute) {
        $pushNotificationToken = $note['value'];
    }
    if ($note['name'] == $slackMSGTS) {
        $tsMSG_ID = $note['value'];
    }
    if($note['name'] == $orderNoteForShortLink){
        $orderNoteShortLinkValue = $note['value'];
    }
}



$order = $response['orders'][0];        
// google short link
if($orderNoteShortLinkValue == ''){
    $request = new Request($googleShortURL);
    $request->setMethod('POST');
    $request->setData(json_encode(array('longUrl' => $shopifyOrderLink.$order['id'])));
    $response = $request->execute();
    $orderNoteShortLinkValue = $response['id'];
    $notesArray[$orderNoteForShortLink] = $response['id'];
}


$slackMSG = $order['name'];
//define the action the we want to do (Reply, Post Message ..etc)
//if fullfilled 
if (strpos(strtolower($order['tags']), strtolower($outGazaCarrier)) !== FALSE) {
    //out side gaza channel
    $channel = 'C6KU0SLSV';
}

if ($order['cancelled_at'] != '') { //update existing 
    $slackMSG = $slackMSG . ' ' . $cancelStatusReaction;
    if ($pushNotificationToken != '') {
        //send Push Notification
        $notificationArr = Array(
            'notification' => array(
                'title' => $cancelPushMSGTitle,
                'body' => $cancelPushMSGBody,
            ),
            'to' => $pushNotificationToken,
        );
    }
    $orderStatus = 'ملغي';
} elseif ($order['financial_status'] == 'paid') { //update existing 
    $slackMSG = $slackMSG . ' ' . $paidStatusReaction;
    if ($pushNotificationToken != '') {
        //send Push Notification
        $notificationArr = Array(
            'notification' => array(
                'title' => $paidStatusPushMSGTitle,
                'body' => $paidStatusPushMSGBody
            ),
            'to' => $pushNotificationToken,
        );
    }
    $orderStatus = 'مدفوع';
} elseif ($order['fulfillment_status'] == 'fulfilled') {
    //get the carriar information 
    $orderStatus = 'شحن';
    $slackMSG = $slackMSG . ' ' . $fullfilledStatusReaction;
    //in Gaza channel
    //get the total information
    if ($pushNotificationToken != '') {
        //send Push Notification
        $notificationArr = Array(
            'notification' => array(
                'title' => $fullFillmentPushMSGTitle,
                'body' => $fullFillmentPushMSGBody,
            ),
            'to' => $pushNotificationToken,
        );
    }
}
$slackMSG.= ' ('.$order['customer']['first_name']. ' ' .$order['customer']['last_name'].')';

$slackMSG.= ' - ('.$order['subtotal_price'].')';
if($order['note'] != ''){
    $slackMSG.= ' -- '.$order['note'];
}
if($orderNoteShortLinkValue != ''){
    $slackMSG.= ' - '.$orderNoteShortLinkValue;
}
/**/
$slackMSGRequestArray = array();
$slackMSGRequestArray['channel'] = $channel;
$slackMSGRequestArray['text'] = $slackMSG;

$request->setHeaders(array(
    'Content-Type:application/json',
    'Authorization:Bearer ' . $token
));
$request->setMethod('POST');

if ($tsMSG_ID != '') { //slack message before
    $slackMSGRequestArray['ts'] = $tsMSG_ID;
    $request->setURL($updatePostMessageEndPoint);
    $request->setData(json_encode($slackMSGRequestArray));
    $slackResponse = $request->execute();
    if(!array_key_exists('ts', $slackResponse)){
        $tsMSG_ID = '';
    }
    
} 
if($tsMSG_ID == ''){//new slack message
	if($orderStatus == 'ملغي'){
		$slackMSGRequestArray['channel'] = $cancelledChannelID;
		$channel = $cancelledChannelID;
	}
    $request->setURL($postMessageEndPoint);
    $request->setData(json_encode($slackMSGRequestArray));
    $slackResponse = $request->execute();
    $tsMSG_ID = $slackResponse['ts'];
    if($tsMSG_ID != ''){
        $notesArray[$slackMSGTS] = $tsMSG_ID;
        //we must update the order with the new message ID
        $postNoteData ['order']['id'] = $order['id'];
        $postNoteData ['order']['note_attributes'] = $notesArray;

        $shopifyParamsURL = $mainURLEndPoint . '/orders/' . $order['id'] . ".json";
        $request->setURL($shopifyParamsURL);
        $request->setHeaders(array(
            'Content-Type:application/json'
            ));    
        $request->setData(json_encode($postNoteData));
        $request->setMethod('PUT');
        $shopifyResponse = $request->execute();
    }
}
//second message for the order status and date change
if($tsMSG_ID != ''){
    $slackMSGRequestArray = array();
    $slackMSGRequestArray['channel'] = $channel;
    $slackMSGRequestArray['text'] = $orderStatus . ' - ' . $todayDate;
    $slackMSGRequestArray['thread_ts'] = $tsMSG_ID;
    $request->setHeaders(array(
        'Content-Type:application/json',
        'Authorization:Bearer ' . $token
    ));    
    $request->setMethod('POST');    
    $request->setURL($postMessageEndPoint);
    $request->setData(json_encode($slackMSGRequestArray));
    $request->execute();
}

// push notification to the client
if ($pushNotificationToken != '' && sizeof($notificationArr) > 0) {

    //send the push notification
    $request->setURL($fcmEndPoint);
    $request->setHeaders(array(
        'Content-Type:application/json',
        'Authorization:key= ' . $webAPIKey,
        'Host:fcm.googleapis.com'
    ));
    $request->setData(json_encode($notificationArr));
    $request->setMethod('POST');
    $response = $request->execute();
}
    //Post the message order with motocycle reaction 
    //if the order contain token for FCM 
        //Post fCM message about fullfillmenet status 
      
//Post the message order 
//Get channel, Messaage Ts 
//Save it in the same order info 
/*
$postNoteData ['order']['id'] = $postOrderInfo['Order_ID'];
$postNoteData ['order']['note_attributes']['slack_message_id'] = $rowData[0];
$shopifyParamsURL = $mainURLEndPoint.$orderDataSet['id'] . ".json";

*/
/***thread_ts 
 * initliaze request

$headers = array(
	'Content-Type:application/json',
        'Authorization:Bearer '.$token
);
$request = new Request($postMessageEndPoint, 'POST', $data);
$request->setHeaders($headers);
$result = $request->execute(false);

echo $result;

/**
 * thread_ts
 * {"channel":"C5R3RPLQZ","text":"I hope the tour went well, <NAME>.","attachments":[{"text":"Who wins the lifetime supply of chocolate?","fallback":"You could be telling the computer exactly what it can do with a lifetime supply of chocolate.","color":"#3AA3E3","attachment_type":"default","callback_id":"select_simple_1234","actions":[{"name":"winners_list","text":"Who should win?","type":"select","data_source":"users"}]}]}

 */<file_sep>/slackWebHooks/setOrderMetaFields.php
<?php

include 'settings.php';
$data = json_decode($data, true);

$mainURL = $mainURLEndPoint . "/orders/" . $data['id'] . "/metafields.json";

if ($data['cancelled_at'] != '') {
    $key = 'cancel_date';
} 
elseif ($data['financial_status'] == 'paid') {
    $key = 'paid_date';
}
elseif ($data['fulfillment_status'] == 'fulfilled') {
    $key = 'fulfill_date';
}

$metaFieldData = array(
    'metafield' => array(
        'namespace' => 'operations',
        'key' => $key,
        'value' => date('d/m/Y h:i:s A'),
        "value_type" => "string"
    )
);
$headers = array(
    'Content-Type:application/json'
);
$request = new Request($mainURL, 'POST', json_encode($metaFieldData));
$request->setHeaders($headers);
$result = $request->execute(false);


echo $result;
<file_sep>/paid.php
<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST,OPTIONS');
header('Cache-Control: no-cache');
header('Pragma: no-cache');
//(0);
session_start();
require_once __DIR__ . '/lib/google/vendor/autoload.php';
define('OAUTH2_CLIENT_ID', '1089990018340-frdjldsicdgrbn7r637b63brstqj0fie.apps.googleusercontent.com');
define('OAUTH2_CLIENT_SECRET', '<KEY>');
$key = file_get_contents('token.txt');
$data = json_decode(file_get_contents('php://input'), true);
// Client init
$client = new Google_Client();
$client->setClientId(OAUTH2_CLIENT_ID);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAccessToken($key);
$client->setClientSecret(OAUTH2_CLIENT_SECRET);
/**
 * Check to see if our access token has expired. If so, get a new one and save it to file for future use.
 */
if ($client->isAccessTokenExpired()) {
    $newToken = json_encode($client->getAccessToken());
    $client->refreshToken($newToken->refresh_token);
    file_put_contents('token.txt', json_encode($client->getAccessToken()));
}
$client->setScopes('https://www.googleapis.com/auth/spreadsheets');
// Define an object that will be used to make all API requests.
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_SESSION[$tokenSessionKey])) {
    $client->setAccessToken($_SESSION[$tokenSessionKey]);
}
if ($client->getAccessToken()) {
    $spreadsheetId = '1v0gHqEXScAqnBg9hudpGfINGyKVQUnS--Co0UVgfBkc';
    $rowData = array();
    /// read from Excel ordersbeforePaid sheet to get the custom data  
    $service = new Google_Service_Sheets($client);
    $orderfoundFlag = false;
    //check if in orders sheet 
    if (!$orderfoundFlag) {
        $range = 'fullfilled!A:E';
        $response = $service->spreadsheets_values->get($spreadsheetId, $range);
        $values = $response->getValues();
        $count = count($values) - 1;
        $i = '';
        if (count($values) == 0) {
            
        } else {
            for ($i = $count; $i >= 0; $i --) {
                // Print columns A and E, which correspond to indices 0 and 4.
                if ($values[$i][1] == $data['name']) {
                    $rowData = $values[$i];
                    break;
                }
            }
        }
        if (sizeof($rowData) > 0) {

            ///Delete the order from Orders Sheet and store it in Fullfilled sheet
            $orderfoundFlag = true;
            $requests[] = new Google_Service_Sheets_Request(array(
                'deleteDimension' => array('range' => array(
                        'sheetId' => 497374135,
                        'dimension' => "ROWS",
                        'startIndex' => $i,
                        'endIndex' => ($i + 1),
                    )
            )));
// Add additional requests (operations) ...

            $batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
                'requests' => $requests
            ));

            $response = $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);
        }
    } elseif (!$orderfoundFlag) {
        //check if in orders sheet 
        $range = 'orders!A:E';

        $response = $service->spreadsheets_values->get($spreadsheetId, $range);
        $values = $response->getValues();
        $count = count($values) - 1;
        $i = '';
        if (count($values) == 0) {
            
        } else {
            for ($i = $count; $i >= 0; $i --) {
                // Print columns A and E, which correspond to indices 0 and 4.
                if ($values[$i][1] == $data['name']) {
                    $rowData = $values[$i];
                    break;
                }
            }
        }
        if (sizeof($rowData) > 0) {
            ///Delete the order from Orders Sheet and store it in Fullfilled sheet
            $orderfoundFlag = true;

            $requests[] = new Google_Service_Sheets_Request(array(
                'deleteDimension' => array('range' => array(
                        'sheetId' => 0,
                        'dimension' => "ROWS",
                        'startIndex' => $i,
                        'endIndex' => ($i + 1),
                    )
            )));
// Add additional requests (operations) ...

            $batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
                'requests' => $requests
            ));

            $response = $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);
        }
    }

/////write on excel 
    $values = array(
        array(
            $data['id'],
            $data['name'],
            $data['customer']['first_name'] . ' ' . $data['customer']['last_name'],
            $data['created_at'],
            $data['total_price']
        // Cell values ...
        ),
            // Additional rows ...
    );
    $range = 'paid!A2:E';
    $body = new Google_Service_Sheets_ValueRange(array(
        'values' => $values
    ));
    $params = array(
        'valueInputOption' => "RAW"
    );
    $result = $service->spreadsheets_values->append($spreadsheetId, $range, $body, $params);
} elseif (OAUTH2_CLIENT_ID == 'REPLACE_ME') {
    $OAUTH2_CLIENT_ID = OAUTH2_CLIENT_ID;
    $htmlBody = <<<END
  <h3>Client Credentials Required</h3>
  <p>
    You need to set <code>\$OAUTH2_CLIENT_ID</code> and
    <code>\$OAUTH2_CLIENT_ID</code> before proceeding.
  <p>
END;
} else {
    // If the user hasn't authorized the app, initiate the OAuth flow
    $state = mt_rand();
    $client->setState($state);
    $_SESSION['state'] = $state;

    $authUrl = $client->createAuthUrl();
    $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
}
?>
<file_sep>/loqtaSendContactEmail.php
<?php
header('Content-Type: application/json');

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
//die(sha1(uniqid("loqta_sendContactEmail", true)));
//f1e1f4421d57660a7fa3bafe7c569eb41899314c
include 'lib/phpmailer/PHPMailerAutoload.php';
error_reporting(0);

$loqtaContactKey = "f1e1f4421d57660a7fa3bafe7c569eb41899314c";
$dateToVeirifyToken = date("d/m/y H");
 

$tokenToVeirify = base64_encode($loqtaContactKey . $dateToVeirifyToken);

$token = $_GET['tt'];
$name = ($_POST['name']) ? $_POST['name'] : '';
$region = ($_POST['region']) ? $_POST['region'] : '';
$mobileNumber = ($_POST['mobileNumber']) ? $_POST['mobileNumber'] : '';
$email = ($_POST['email']) ? $_POST['email'] : '';
$reason = ($_POST['reason']) ? $_POST['reason'] : '';
$subject = ($_POST['subject']) ? $_POST['subject'] : '';
$message = ($_POST['message']) ? $_POST['message'] : '';
$subjectToSend = "Loqta Subject: ".$subject;
$formatedMessageToSend = "Name:".$name." <br><br> Region:".$region." <br><br> Mobile Number:".$mobileNumber." <br><br> Email:".$email."<br><br> Reason:".$reason."<br><br> Message:".$message." ";

if ($tokenToVeirify != $token) {
    $resultStatus = false;
    $resultMessages['status'] = false;
    $resultMessages['message'] = 'Invalid Token, Or Expired Token';
    echo json_encode($resultMessages);
    
}else{





//Load Composer's autoloader

$mail = new PHPMailer();                              // Passing `true` enables exceptions
try {


       // $mail->IsSMTP(); // telling the class to use SMTP
        $mail->SMTPDebug = 0;                     // enables SMTP debug information (for testing)
        // 1 = errors and messages
        // 2 = messages only
        $mail->SMTPAuth = true;                  // enable SMTP authentication
        $mail->SMTPSecure = "tls";
        $mail->Host = "smtp.gmail.com";      // SMTP server
        $mail->Port = 587;                   // SMTP port
        $mail->Username = "<EMAIL>";  // username
        $passord = <PASSWORD>";
        $mail->Password = $<PASSWORD>;            // password
        
        $mail->SetFrom('<EMAIL>', 'Loqta');
        $mail->Subject = $subjectToSend;
        $mail->MsgHTML($formatedMessageToSend);
      //Recipients
       $mail->AddAddress('<EMAIL>');     // Add a recipient
        $mail->AddCC('<EMAIL>');

      $mail->isHTML(true);                                  // Set email format to HTML
      $mail->Body    = $formatedMessageToSend;
    

    if($mail->send()){
      $resultMessages['status'] = true;
    $resultMessages['message'] = 'send!!';
    echo json_encode($resultMessages);
    }else{
       $resultMessages['status'] = false;
      
    $resultMessages['message'] = 'Message could not be sent. Mailer Error: '. $mail->ErrorInfo;
    echo json_encode($resultMessages);
    }
} catch (Exception $e) {
      $resultMessages['status'] = false;
      
    $resultMessages['message'] = 'Message could not be sent. Mailer Error: '. $mail->ErrorInfo;
    echo json_encode($resultMessages);
    
}
}<file_sep>/slackWebHooks/settings.php
<?php 
error_reporting(0);
include 'request.php';

$mainURLEndPoint = 'https://f3aa0d6659405ab34f9c0af85d0f2ef9:590b142f0e9922bd187703cd6729bae8@loqta-ps.myshopify.com/admin';
$shopifyOrderLink = 'https://loqta-ps.myshopify.com/admin/orders/';
$googleKey = '<KEY>';
$googleShortURL = "https://www.googleapis.com/urlshortener/v1/url?key=${googleKey}";
$data = file_get_contents('php://input');
$postOrderInfo = array();

if(!defined('NO_DEFAULT_HEADERS')){
    header('Content-Type: application/json');
    header('Accept: application/json');
}
date_default_timezone_set ( 'Asia/Gaza' );
