CustomerCreationWebhookController.php (Before) CustomerCreationWebhookController.php (After)
<?php <?php
   
namespace App\Http\Controllers; namespace App\Http\Controllers;
   
use DB; use DB;
use Log; use Log;
use App\Users; use App\Users;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Http\ResponseHelper; use App\Http\ResponseHelper;
use App\Jobs\GenerateUserTokenJob; use App\Jobs\GenerateUserTokenJob;
use Config; use Config;
use OhMyBrew\BasicShopifyAPI; use OhMyBrew\BasicShopifyAPI;
   
class CustomerCreationWebhookController extends Controller class CustomerCreationWebhookController extends Controller
{ {
   
   private $helper;    private $helper;
   private $shopifyProductDao;    private $shopifyProductDao;
   private $sharedSecret;    private $sharedSecret;
   private $randomString;    private $randomString;
   private $shopify_api_version;    private $shopify_api_version;
   
   public function __construct()    public function __construct()
   {    {
       $this->helper = new ResponseHelper();        $this->helper = new ResponseHelper();
       $this->shopify_api_version = env('SHOPIFY_API_VERSION', true);        $this->shopify_api_version = env('SHOPIFY_API_VERSION', true);
   }    }
   
   function processWebhook()    function processWebhook()
   {          {      
   
.        $this->sharedSecret  = Config::get('shopify.secret');        $this->sharedSecret  = Config::get('shopify.secretWebhook');
       $this->webhookContent    = $this->webhook($this->sharedSecret);        $this->webhookContent    = $this->webhook($this->sharedSecret);
                 
       $this->randomString = $this->generateRandomString(16);        $this->randomString = $this->generateRandomString(16);
   
       $lastInsertedId = DB::table('webhooks')->insertGetId(        $lastInsertedId = DB::table('webhooks')->insertGetId(
.        [            [
             'webhookContent' => $this->webhookContent,                'webhookContent' => $this->webhookContent,
             'authToken' => $this->randomString                'authToken' => $this->randomString
           ]            ]
       );        );
   
       dispatch(new GenerateUserTokenJob($this->webhookContent, $this->randomString));        dispatch(new GenerateUserTokenJob($this->webhookContent, $this->randomString));
   
       return 'true';        return 'true';
                 
   }    }
   
   function webhook($my_shared_secret){    function webhook($my_shared_secret){
                 
       define('SHOPIFY_APP_SECRET', 'my_shared_secret');        define('SHOPIFY_APP_SECRET', 'my_shared_secret');
       $hmac_header = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'];        $hmac_header = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'];
       $data        = file_get_contents('php://input');        $data        = file_get_contents('php://input');
       $verified    = $this->verify_webhook($data, $hmac_header);        $verified    = $this->verify_webhook($data, $hmac_header);
       error_log('Webhook verified: '.var_export($verified, true));        error_log('Webhook verified: '.var_export($verified, true));
       return $data;        return $data;
   
   }    }
   
   function verify_webhook($data, $hmac_header){    function verify_webhook($data, $hmac_header){
   
       $calculated_hmac = base64_encode(hash_hmac('sha256', $data, SHOPIFY_APP_SECRET, true));        $calculated_hmac = base64_encode(hash_hmac('sha256', $data, SHOPIFY_APP_SECRET, true));
       return ($hmac_header==$calculated_hmac);        return ($hmac_header==$calculated_hmac);
   
   }    }
   
   function generateRandomString($length) {    function generateRandomString($length) {
       $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
       $charactersLength = strlen($characters);        $charactersLength = strlen($characters);
       $randomString = '';        $randomString = '';
       for ($i = 0; $i < $length; $i++) {        for ($i = 0; $i < $length; $i++) {
           $randomString .= $characters[rand(0, $charactersLength - 1)];            $randomString .= $characters[rand(0, $charactersLength - 1)];
       }        }
       return $randomString;        return $randomString;
   }    }
         
   public function handleWebhookData()    public function handleWebhookData()
   {    {
       Log::channel('cron')->info('testing webhook');        Log::channel('cron')->info('testing webhook');
                 
       $api = new BasicShopifyAPI();        $api = new BasicShopifyAPI();
   
.        $password   = Config::get('shopify.password');        $password   = Config::get('shopify.passwordWebhook');
       $shopDomain = Config::get('shopify.shopDomain');        $shopDomain = Config::get('shopify.shopDomainWebhook');
   
       $api->setShop($shopDomain);        $api->setShop($shopDomain);
       $api->setAccessToken($password);        $api->setAccessToken($password);
   
.        $webhookDetails = DB::table('webhooks')->get();        $webhookDetails = DB::table('webhooks')->where([ 
             ['status', '=', '0'] 
         ])->get();
   
       if(!empty($webhookDetails)){        if(!empty($webhookDetails)){
.             $updateIds = array();
           foreach($webhookDetails as $webhookData){            foreach($webhookDetails as $webhookData){
               $webhookContent = $webhookData->webhookContent;                $webhookContent = $webhookData->webhookContent;
               $authToken  = $webhookData->authToken;                $authToken  = $webhookData->authToken;
.                 $webhookId = $webhookData->id; 
               $webhook = json_decode($webhookContent);                $webhook = json_decode($webhookContent);
   
               $email = $webhook->email;                $email = $webhook->email;
               $customerId  = $webhook->id;                $customerId  = $webhook->id;
   
               $metafieldArray = array();                $metafieldArray = array();
   
               $temp['key']        = 'authToken';                $temp['key']        = 'authToken';
               $temp['value']      = $authToken;                $temp['value']      = $authToken;
               $temp['value_type'] = 'string';                $temp['value_type'] = 'string';
               $temp['namespace']  = 'global';                $temp['namespace']  = 'global';
                                 
               array_push($metafieldArray, $temp);                array_push($metafieldArray, $temp);
   
               $user = DB::table('users')->where('user_email', '=', $email)->get();                $user = DB::table('users')->where('user_email', '=', $email)->get();
                 
               if(!isset($user[0]->user_email)){                if(!isset($user[0]->user_email)){
                   // create user in DB                    // create user in DB
                   $userId = DB::table('users')->insertGetId([                    $userId = DB::table('users')->insertGetId([
                       'user_email' => $email,                        'user_email' => $email,
                       'status' => 1,                        'status' => 1,
                       'auth_token' => $authToken                        'auth_token' => $authToken
                   ]);                    ]);
               }                }
               else                else
               {                {
                   $userId = DB::table('users')->where('user_email', $email)->update(['auth_token' => $authToken]);                      $userId = DB::table('users')->where('user_email', $email)->update(['auth_token' => $authToken]);  
                                         
               }                }
   
               $method = 'GET';                $method = 'GET';
               $url    = '/admin/api/'.$this->shopify_api_version.'/customers/'.$customerId.'/metafields.json';                $url    = '/admin/api/'.$this->shopify_api_version.'/customers/'.$customerId.'/metafields.json';
               $params = null;                $params = null;
               $result = $api->rest($method, $url, $params);                $result = $api->rest($method, $url, $params);
   
               if(empty($result->errors))                if(empty($result->errors))
               {                {
                   $metafields = $result->body->metafields;                    $metafields = $result->body->metafields;
   
                   if(!empty($metafields)){                    if(!empty($metafields)){
                       $updated = false;                        $updated = false;
                       foreach($metafields as $metafield){                        foreach($metafields as $metafield){
                         
                           $metaId        = $metafield->id;                            $metaId        = $metafield->id;
                           $metaKey       = $metafield->key;                            $metaKey       = $metafield->key;
                           $metaNameSpace = $metafield->namespace;                            $metaNameSpace = $metafield->namespace;
                         
                           if($metaKey == 'authToken' && $metaNameSpace == 'global'){                            if($metaKey == 'authToken' && $metaNameSpace == 'global'){
                         
                               // update Metafield                                // update Metafield
                               $updateRequest = [];                                $updateRequest = [];
                               $updateRequest['metafield']['id']         = $metaId;                                $updateRequest['metafield']['id']         = $metaId;
                               $updateRequest['metafield']['value']      = $authToken;                                $updateRequest['metafield']['value']      = $authToken;
                               $updateRequest['metafield']['value_type'] = "string";                                $updateRequest['metafield']['value_type'] = "string";
                         
                               $params = $updateRequest;                                $params = $updateRequest;
                                                 
                               $method = 'PUT';                                $method = 'PUT';
                               $url    = '/admin/api/'.$this->shopify_api_version.'/metafields/'.$metaId.'.json';                                $url    = '/admin/api/'.$this->shopify_api_version.'/metafields/'.$metaId.'.json';
                               $result = $api->rest($method, $url, $params);                                $result = $api->rest($method, $url, $params);
                         
                               if(!empty($result->body->metafield)){                                if(!empty($result->body->metafield)){
                                   // Updated succesfully                                    // Updated succesfully
                                   $updated = true;                                    $updated = true;
                                   Log::channel('cron')->info("Updated metafield successgully for the user ".$customerId." with value ".$authToken);                                    Log::channel('cron')->info("Updated metafield successgully for the user ".$customerId." with value ".$authToken);
.                                                                         $updateIds[] = $webhookId;    
                               }                                }
                               else{                                else{
                                   // not updated                                    // not updated
                                   $updated = false;                                    $updated = false;
                                   Log::channel('cron')->info("Failed to update metafield for the user ".$customerId." with value ".$authToken);                                    Log::channel('cron')->info("Failed to update metafield for the user ".$customerId." with value ".$authToken);
.                                 //   Log::channel('cron')->info(print_r($result,1));                                     Log::channel('cron')->info(json_encode($result));                                     
                               }                                }
                                                 
                           }                            }
                         
                       }                        }
                         
                       if($updated == false){                        if($updated == false){
                         
.                            $this->createCustomerMetafield($metafieldArray, $customerId, $authToken, $api);                             $createMetaResult = $this->createCustomerMetafield($metafieldArray, $customerId, $authToken, $webhookId); 
                             if($createMetaResult){ 
                                 $updateIds[] = $webhookId; 
                             } 
                       }                        }
                   }else{                    }else{
                                                 
.                        $this->createCustomerMetafield($metafieldArray, $customerId, $authToken, $api);                         $createMetaResult = $this->createCustomerMetafield($metafieldArray, $customerId, $authToken, $webhookId); 
                         if($createMetaResult){ 
                             $updateIds[] = $webhookId; 
                         } 
                                 
                   }                    }
   
               }                }
   
           }            }
.             if(!empty($updateIds)){
                 DB::table('webhooks')->whereIn('id',$updateIds)->update(['status' => 1]);
             }
         }
         else{
             Log::channel('cron')->info("Empty Webhook Data");
       }        }
                 
   }    }
   
.    function createCustomerMetafield($metafield, $customerId, $authToken, $api){    function createCustomerMetafield($metafield, $customerId, $authToken, $webhookId){
                 
.         $api = new BasicShopifyAPI();
   
         $password = Config::get('shopify.passwordCustomer');
         $shopDomain = Config::get('shopify.shopDomainCustomer');
   
         $api->setShop($shopDomain);
         $api->setAccessToken($password);
       $params = array(        $params = array(
           'customer' => array(            'customer' => array(
               'id' => $customerId,                'id' => $customerId,
               'metafields' => $metafield                'metafields' => $metafield
           )            )
       );        );
   
       $method = 'PUT';        $method = 'PUT';
       $url = '/admin/api/'.$this->shopify_api_version.'/customers/'.$customerId.'.json';        $url = '/admin/api/'.$this->shopify_api_version.'/customers/'.$customerId.'.json';
   
       $result = $api->rest($method, $url, $params);        $result = $api->rest($method, $url, $params);
   
       if(!empty($result->body->customer)){        if(!empty($result->body->customer)){
           // Updated customer succssfully by adding new metafield            // Updated customer succssfully by adding new metafield
           $updated = true;            $updated = true;
           Log::channel('cron')->info("Updated customer succssfully by adding new metafield ".$customerId." with value ".$authToken);            Log::channel('cron')->info("Updated customer succssfully by adding new metafield ".$customerId." with value ".$authToken);
.                         return true; 
       }        }
       else{        else{
           // not updated            // not updated
           $updated = false;            $updated = false;
           Log::channel('cron')->info("Failed to update customer metafield for the user ".$customerId." with value ".$authToken);            Log::channel('cron')->info("Failed to update customer metafield for the user ".$customerId." with value ".$authToken);
.        //  Log::channel('cron')->info(print_r($result,1));             Log::channel('cron')->info(json_encode($result)); 
             return false; 
       }        }
   }    }
         
   
         
   
} }
.