vijayrami

php artisan ebay:importimages

Jul 6th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 16.09 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Console\Commands;
  4.  
  5. use Illuminate\Console\Command;
  6.  
  7. use Illuminate\Support\Facades\DB;
  8.  
  9. use App\Ebay\EBaySessionProduct;
  10.  
  11. class EbayImportImages extends Command
  12. {
  13.     /**
  14.      * The name and signature of the console command.
  15.      *
  16.      * @var string
  17.      */
  18.     protected $signature = 'ebay:importimages';
  19.    
  20.     /**
  21.      * The console command description.
  22.      *
  23.      * @var string
  24.      */
  25.     protected $description = 'Import your Product Images into Ebay';
  26.    
  27.     const NOT_IMPORT_STATUS = '1';
  28.    
  29.     const NO_XML_RESPONSE_STATUS = '2';
  30.    
  31.     const EBAY_ERROR_STATUS = '3';
  32.    
  33.     const EBAY_PRO_NO_IMG_STATUS = '4';
  34.    
  35.     const EBAY_IMAGE_VERB = 'UploadSiteHostedPictures';
  36.    
  37.     const EBAY_SERVER_URL = 'https://api.ebay.com/ws/api.dll';
  38.    
  39.     /**
  40.      * Create a new command instance.
  41.      *
  42.      * @return void
  43.      */
  44.     public function __construct()
  45.     {
  46.         parent::__construct();
  47.     }
  48.     public function register()
  49.     {
  50.         $this->app->bind('EBaySessionProduct', function () {
  51.             return new EBaySessionProduct;
  52.         });
  53.     }
  54.     /**
  55.      * Execute the console command.
  56.      *
  57.      * @return mixed
  58.      */
  59.     public function handle()
  60.     {
  61.         $cronName = \App\Constants::CRON_EBAY['UPLOAD_IMAGES'];
  62.         $cronExist = \App\CronDetail::where('cron_name', $cronName)->first();
  63.        
  64.         if ($cronExist)
  65.         $startDate = date('Y-m-d H:i:s');
  66.         $getadmindata = DB::table('tbl_admin_ebay_setting')->first();
  67.         $import_designer_id = $getadmindata->ebay_designer_import_product_id;
  68.         $import_products = DB::table('tbl_ebay_products')
  69.             ->join('tbl_magento_products', 'tbl_ebay_products.mage_pid', '=', 'tbl_magento_products.mp_pid')
  70.             ->join('tbl_products', 'tbl_ebay_products.magento_id', '=', 'tbl_products.mage_pid')
  71.             ->whereNull('tbl_ebay_products.cron_error')
  72.             ->select('tbl_ebay_products.*', 'tbl_magento_products.*', 'tbl_products.*')
  73.             ->where([['tbl_products.designer_id', '=', $import_designer_id], ['tbl_products.processed_status', '=', 1],['tbl_products.for_ebay', '=', 1], ['tbl_products.product_status', '=', '1']])
  74.             ->whereIn('tbl_ebay_products.product_ebay_status', array(EbayImportImages::NOT_IMPORT_STATUS,EbayImportImages::NO_XML_RESPONSE_STATUS,EbayImportImages::EBAY_ERROR_STATUS,EbayImportImages::EBAY_PRO_NO_IMG_STATUS))
  75.             ->offset(0)->limit(1)
  76.             ->orderBy('tbl_magento_products.mp_pid', 'asc')
  77.             ->groupBy('tbl_magento_products.mp_pid')
  78.             ->get();
  79.         //echo "<pre>";print_r($import_products);exit;
  80.         $fullurl = $checkImageExist = $emptyArr = array();
  81.         $verb = EbayImportImages::EBAY_IMAGE_VERB;
  82.        
  83.         $devID = config('ebay.Dev_ID');
  84.         $appID = config('ebay.App_ID');
  85.         $certID = config('ebay.Cert_ID');
  86.         $comp_version = config('ebay.COMPATIBILITY_LEVEL');
  87.         $ebay_server_url = config('ebay.SERVER_URL');
  88.         if (count($import_products) > 0) {
  89.         foreach ($import_products as $import_product) {
  90.             try {
  91.             $designer_general_settings = \App\Designer::where('designer_id', '=', $import_product->designer_id)->first();
  92.             if ($designer_general_settings['is_ebay_shirtee_api_on'] == 1) {
  93.             $ebay_setting = \App\EbaySetting::where('designer_id', '=', $import_product->designer_id)->first();
  94.            
  95.             $mediaList = \App\Helpers\AppHelper::instance()->callMagentoApi('catalog_product_attribute_media.list', ['productId' => $import_product->magento_id], $import_product->designer_id);
  96.            
  97.             $mediaListSort = $this->array_msort($mediaList, array('label' => SORT_ASC));
  98.             $pdatas = $mediaListSort;
  99.             $pdatas_options = json_decode($import_product->mp_options);
  100.             //echo "<pre>";print_r($pdatas_options);exit;
  101.             if (!empty($pdatas) && $pdatas != '') {
  102.             foreach ($pdatas as $pdata_key => $pdata_value) {
  103.                 if ($import_product->product_ebay_id != '')
  104.                 {
  105.                     $image_path = '';
  106.                     $imagesUrl = unserialize($import_product->ebay_image_urls);
  107.                     if (!in_array($pdata_value['label'], $imagesUrl[$pdata_key]))
  108.                     {
  109.                         $checkImageExist[] = $pdata_value['label'];
  110.                         $image_path = $pdata_value['url'];
  111.                     } else {
  112.                         $emptyArr[] = $pdata_value['label'];
  113.                     }
  114.                 } else {
  115.                     $image_path = $pdata_value['url'];
  116.                 }
  117.                 if($image_path != '')
  118.                 {
  119.                     $real_path = $this->getRedirectAfterpath($image_path);
  120.                     // xml creation code start for upload image services
  121.                     ///Build the request Xml string
  122.                     $requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
  123.                     $requestXmlBody.= '<UploadSiteHostedPicturesRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
  124.                     $requestXmlBody.= "<RequesterCredentials><eBayAuthToken>".$ebay_setting->production_user_tocken."</eBayAuthToken></RequesterCredentials>";
  125.                     $requestXmlBody.= '<ErrorLanguage>en_US</ErrorLanguage>';
  126.                     $requestXmlBody.= "<Version>".$comp_version."</Version>";
  127.                     $requestXmlBody.= "<ExternalPictureURL>".$real_path."</ExternalPictureURL>";
  128.                     $requestXmlBody.= '</UploadSiteHostedPicturesRequest>';
  129.                     // xml creation code ends for upload image services
  130.                     //Create a new eBay session with all details pulled in from included keys.php
  131.                     //echo $requestXmlBody;exit;
  132.                     $session = new \EBaySessionProduct($ebay_setting->production_user_tocken, $devID, $appID, $certID, $ebay_server_url, $comp_version, $ebay_setting->ebay_site_id, $verb);
  133.                     //send the request and get response
  134.                     $responseXml = $session->sendHttpRequest($requestXmlBody);
  135.                     //echo "<pre>";print_r($responseXml);echo "</pre>";exit;
  136.                     if (stristr($responseXml, 'HTTP 404') || $responseXml == ''){
  137.                     \App\EbayListProduct::where('magento_id', $import_product->magento_id)->update(['product_ebay_status' => '2'],['cron_error' => '']);
  138.                     \Log::channel('ebay')->info('Ebay not getting any response during image upload for product id - ' . $import_product->magento_id);
  139.                     } else {
  140.                         $responseDoc = new \DomDocument();
  141.                         $responseDoc->loadXML($responseXml);
  142.                         $errors = $responseDoc->getElementsByTagName('Errors');
  143.                         if ($errors->length == 0) {
  144.                             $responses = $responseDoc->getElementsByTagName("UploadSiteHostedPicturesResponse");
  145.                             foreach ($responses as $response) {
  146.                                 $acks = $response->getElementsByTagName("Ack");
  147.                                 $ack = $acks->item(0)->nodeValue;
  148.                                 //echo "Ack = $ack <BR />\n";   // Success if successful
  149.                                 $picturesDatas = $response->getElementsByTagName("SiteHostedPictureDetails");
  150.                                 //$array = iterator_to_array($picturesDatas);
  151.                                 foreach ($picturesDatas as $picturesData) {
  152.                                     $fullurls = $picturesData->getElementsByTagName("FullURL");
  153.                                     //$fullurl[]   = $fullurls->item(0)->nodeValue;
  154.                                     array_push($fullurl, array($fullurls->item(0)->nodeValue, $pdata_value['label']));
  155.                                 }
  156.                             }
  157.                         } else {
  158.                             $error = $errors->item(0)->getElementsByTagName('SeverityCode');
  159.                             $errorDB = $error->item(0)->nodeValue;
  160.                             if ($errors->length > 0 && $errorDB != 'Warning') {
  161.                                 $code = $errors->item(0)->getElementsByTagName('ErrorCode');
  162.                                 $shortMsg = $errors->item(0)->getElementsByTagName('ShortMessage');
  163.                                 $longMsg = $errors->item(0)->getElementsByTagName('LongMessage');
  164.                                 $codeDB = $code->item(0)->nodeValue;
  165.                                 $shortMsgDB = (count($shortMsg) > 0) ? str_replace(">", "&gt;", str_replace("<", "&lt;", $shortMsg->item(0)->nodeValue)) : '';
  166.                                 $longMsgDB = (count($longMsg) > 0) ? str_replace(">", "&gt;", str_replace("<", "&lt;", $longMsg->item(0)->nodeValue)) : '';
  167.                                 \App\EbayListProduct::where('magento_id', $import_product->magento_id)->update(['product_ebay_status' => '3', 'error' => $errorDB, 'error_code' => $codeDB, 'error_short_msg' => $shortMsgDB, 'error_long_msg' => $longMsgDB,'cron_error' => '']);
  168.                             } else {
  169.                                 $responses = $responseDoc->getElementsByTagName("UploadSiteHostedPicturesResponse");
  170.                                 foreach ($responses as $response) {
  171.                                     $acks = $response->getElementsByTagName("Ack");
  172.                                     $ack = $acks->item(0)->nodeValue;
  173.                                     //echo "Ack = $ack <BR />\n";   // Success if successful
  174.                                     $picturesDatas = $response->getElementsByTagName("SiteHostedPictureDetails");
  175.                                     //$array = iterator_to_array($picturesDatas);
  176.                                     foreach ($picturesDatas as $picturesData) {
  177.                                         $fullurls = $picturesData->getElementsByTagName("FullURL");
  178.                                         //$fullurl[]   = $fullurls->item(0)->nodeValue;
  179.                                         //array_push($fullurl, $fullurls->item(0)->nodeValue);
  180.                                         array_push($fullurl, array($fullurls->item(0)->nodeValue, $pdata_value['label']));
  181.                                     }
  182.                                 }
  183.                             }
  184.                         }
  185.                     }
  186.                 }
  187.             }
  188.             } else {
  189.                 $no_image_error = "Ebay Require atleat one image for product.
  190.    But Below product have no image.";
  191.                 $no_image_error.= "Product ID = $import_product->magento_id
  192. Product SKU = $import_product->mp_sku";
  193.                 \Mail::raw($no_image_error, function ($message) {
  194.                     $message->to('[email protected]')->bcc('[email protected]')->subject('Product Have No Images - Ebay Error');
  195.                 });
  196.                 \Log::channel('ebay')->error('This Product have no images : Product ID -' . $import_product->magento_id . ' Product SKU = ' . $import_product->mp_sku);
  197.                 \App\EbayListProduct::where('magento_id', $import_product->magento_id)->update(['product_ebay_status' => '4', 'ebay_status' => 'No Image','cron_error' => '']);
  198.             }
  199.                         if (is_array($fullurl) && count($fullurl) > 0) {
  200.                             if ($import_product->product_ebay_id != '') {
  201.                                 if (is_array($checkImageExist) && count($checkImageExist) > 0) {
  202.                                     $imagesUrl = unserialize($import_product->ebay_image_urls);
  203.                                     if(empty($imagesUrl))
  204.                                     {
  205.                                         $serializedFullUrlArr = serialize($fullurl);
  206.                                     }
  207.                                     else
  208.                                     {
  209.                                         $serializedFullUrlArr = serialize(array_merge($imagesUrl, $fullurl));
  210.                                     }
  211.                                 }
  212.                             } else {
  213.                                 $serializedFullUrlArr = serialize($fullurl);
  214.                             }
  215.                             \App\EbayListProduct::where('magento_id', $import_product->magento_id)->update(['product_ebay_status' => '5', 'error' => '', 'error_code' => '', 'error_short_msg' => '', 'error_long_msg' => '', 'ebay_status' => 'Image Uploaded', 'ebay_image_urls' => $serializedFullUrlArr, 'cron_error' => NULL]);
  216.                             if ($cronExist) {
  217.                                 $endDate = date('Y-m-d H:i:s');
  218.                                 callChannel($startDate, $endDate, $cronExist->id, 'ebay');
  219.                             }
  220.                             \Log::channel('ebay')->info('Ebay Import Image script run successfully.');
  221.                         }
  222.  
  223.                         if ((is_array($emptyArr) && count($emptyArr) > 0) && ($import_product->product_ebay_id != '')) {
  224.                             \App\EbayListProduct::where('magento_id', $import_product->magento_id)->update(['product_ebay_status' => '5', 'error' => '', 'error_code' => '', 'error_short_msg' => '', 'error_long_msg' => '', 'ebay_status' => 'Image Uploaded','cron_error' => NULL]);
  225.                         }
  226.                     }
  227.                 }
  228.                 catch(\Exception $e) {
  229.                     $designerDetials = \App\Designer::where('designer_id', $import_product->designer_id)->first();
  230.                     $designerSettings = \App\Setting::where('designer_id', $import_product->designer_id)->first();
  231.                     \App\EbayListProduct::where('magento_id', $import_product->magento_id)->update(['cron_error' => $e->getMessage() ]);
  232.                     $cron_error = "Designer ID = $import_product->designer_id
  233.            Designer Name = $designerDetials->designer_name
  234.            Designer Email = $designerDetials->designer_email
  235.            Designer API Username = $designerSettings->username
  236.            Designer API Password = $designerSettings->password
  237.            Magento id = $import_product->magento_id";
  238.                     \Mail::raw($cron_error, function ($message) {
  239.                         $message->to('[email protected]')
  240.                         ->bcc('[email protected]')
  241.                         ->subject('Ebay Import Images Cron Error');
  242.                     });
  243.                     app('db')->rollback();
  244.                     \Log::channel('ebay')->error('Error while uploading Ebay images :' . $e->getMessage() . ' For Designer ID = ' . $import_product->designer_id . ' Designer Name = ' . $designerDetials->designer_name . ' Designer Email = ' . $designerDetials->designer_email . ' Designer API Username = ' . $designerSettings->username . ' Designer API Password = ' . $designerSettings->password . ' Magento id = ' . $import_product->magento_id);
  245.                 }
  246.             } // import products loop ends
  247.         }
  248.     }
  249.     public function array_msort($array, $cols) {
  250.         $colarr = array();
  251.         foreach ($cols as $col => $order) {
  252.             $colarr[$col] = array();
  253.             foreach ($array as $k => $row) {
  254.                 $colarr[$col]['_' . $k] = strtolower($row[$col]);
  255.             }
  256.         }
  257.         $eval = 'array_multisort(';
  258.         foreach ($cols as $col => $order) {
  259.             $eval.= '$colarr[\'' . $col . '\'],' . $order . ',';
  260.         }
  261.         $eval = substr($eval, 0, -1) . ');';
  262.         eval($eval);
  263.         $ret = array();
  264.         foreach ($colarr as $col => $arr) {
  265.             foreach ($arr as $k => $v) {
  266.                 $k = substr($k, 1);
  267.                 if (!isset($ret[$k])) $ret[$k] = $array[$k];
  268.                 $ret[$k][$col] = $array[$k][$col];
  269.             }
  270.         }
  271.         return $ret;
  272.     }
  273.     public function getRedirectAfterpath($url)
  274.     {
  275.         $ch = curl_init();
  276.         curl_setopt($ch, CURLOPT_URL, $url);
  277.         curl_setopt($ch, CURLOPT_HEADER, true);
  278.         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true so that PHP follows any "Location:" header
  279.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  280.        
  281.         $a = curl_exec($ch); // $a will contain all headers
  282.        
  283.         $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL
  284.        
  285.         return $url; // Voila
  286.     }
  287. }
Advertisement
Add Comment
Please, Sign In to add comment