Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Console\Commands;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\DB;
- use App\Ebay\EBaySessionProduct;
- class EbayImportImages extends Command
- {
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'ebay:importimages';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = 'Import your Product Images into Ebay';
- const NOT_IMPORT_STATUS = '1';
- const NO_XML_RESPONSE_STATUS = '2';
- const EBAY_ERROR_STATUS = '3';
- const EBAY_PRO_NO_IMG_STATUS = '4';
- const EBAY_IMAGE_VERB = 'UploadSiteHostedPictures';
- const EBAY_SERVER_URL = 'https://api.ebay.com/ws/api.dll';
- /**
- * Create a new command instance.
- *
- * @return void
- */
- public function __construct()
- {
- parent::__construct();
- }
- public function register()
- {
- $this->app->bind('EBaySessionProduct', function () {
- return new EBaySessionProduct;
- });
- }
- /**
- * Execute the console command.
- *
- * @return mixed
- */
- public function handle()
- {
- $cronName = \App\Constants::CRON_EBAY['UPLOAD_IMAGES'];
- $cronExist = \App\CronDetail::where('cron_name', $cronName)->first();
- if ($cronExist)
- $startDate = date('Y-m-d H:i:s');
- $getadmindata = DB::table('tbl_admin_ebay_setting')->first();
- $import_designer_id = $getadmindata->ebay_designer_import_product_id;
- $import_products = DB::table('tbl_ebay_products')
- ->join('tbl_magento_products', 'tbl_ebay_products.mage_pid', '=', 'tbl_magento_products.mp_pid')
- ->join('tbl_products', 'tbl_ebay_products.magento_id', '=', 'tbl_products.mage_pid')
- ->whereNull('tbl_ebay_products.cron_error')
- ->select('tbl_ebay_products.*', 'tbl_magento_products.*', 'tbl_products.*')
- ->where([['tbl_products.designer_id', '=', $import_designer_id], ['tbl_products.processed_status', '=', 1],['tbl_products.for_ebay', '=', 1], ['tbl_products.product_status', '=', '1']])
- ->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))
- ->offset(0)->limit(1)
- ->orderBy('tbl_magento_products.mp_pid', 'asc')
- ->groupBy('tbl_magento_products.mp_pid')
- ->get();
- //echo "<pre>";print_r($import_products);exit;
- $fullurl = $checkImageExist = $emptyArr = array();
- $verb = EbayImportImages::EBAY_IMAGE_VERB;
- $devID = config('ebay.Dev_ID');
- $appID = config('ebay.App_ID');
- $certID = config('ebay.Cert_ID');
- $comp_version = config('ebay.COMPATIBILITY_LEVEL');
- $ebay_server_url = config('ebay.SERVER_URL');
- if (count($import_products) > 0) {
- foreach ($import_products as $import_product) {
- try {
- $designer_general_settings = \App\Designer::where('designer_id', '=', $import_product->designer_id)->first();
- if ($designer_general_settings['is_ebay_shirtee_api_on'] == 1) {
- $ebay_setting = \App\EbaySetting::where('designer_id', '=', $import_product->designer_id)->first();
- $mediaList = \App\Helpers\AppHelper::instance()->callMagentoApi('catalog_product_attribute_media.list', ['productId' => $import_product->magento_id], $import_product->designer_id);
- $mediaListSort = $this->array_msort($mediaList, array('label' => SORT_ASC));
- $pdatas = $mediaListSort;
- $pdatas_options = json_decode($import_product->mp_options);
- //echo "<pre>";print_r($pdatas_options);exit;
- if (!empty($pdatas) && $pdatas != '') {
- foreach ($pdatas as $pdata_key => $pdata_value) {
- if ($import_product->product_ebay_id != '')
- {
- $image_path = '';
- $imagesUrl = unserialize($import_product->ebay_image_urls);
- if (!in_array($pdata_value['label'], $imagesUrl[$pdata_key]))
- {
- $checkImageExist[] = $pdata_value['label'];
- $image_path = $pdata_value['url'];
- } else {
- $emptyArr[] = $pdata_value['label'];
- }
- } else {
- $image_path = $pdata_value['url'];
- }
- if($image_path != '')
- {
- $real_path = $this->getRedirectAfterpath($image_path);
- // xml creation code start for upload image services
- ///Build the request Xml string
- $requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
- $requestXmlBody.= '<UploadSiteHostedPicturesRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
- $requestXmlBody.= "<RequesterCredentials><eBayAuthToken>".$ebay_setting->production_user_tocken."</eBayAuthToken></RequesterCredentials>";
- $requestXmlBody.= '<ErrorLanguage>en_US</ErrorLanguage>';
- $requestXmlBody.= "<Version>".$comp_version."</Version>";
- $requestXmlBody.= "<ExternalPictureURL>".$real_path."</ExternalPictureURL>";
- $requestXmlBody.= '</UploadSiteHostedPicturesRequest>';
- // xml creation code ends for upload image services
- //Create a new eBay session with all details pulled in from included keys.php
- //echo $requestXmlBody;exit;
- $session = new \EBaySessionProduct($ebay_setting->production_user_tocken, $devID, $appID, $certID, $ebay_server_url, $comp_version, $ebay_setting->ebay_site_id, $verb);
- //send the request and get response
- $responseXml = $session->sendHttpRequest($requestXmlBody);
- //echo "<pre>";print_r($responseXml);echo "</pre>";exit;
- if (stristr($responseXml, 'HTTP 404') || $responseXml == ''){
- \App\EbayListProduct::where('magento_id', $import_product->magento_id)->update(['product_ebay_status' => '2'],['cron_error' => '']);
- \Log::channel('ebay')->info('Ebay not getting any response during image upload for product id - ' . $import_product->magento_id);
- } else {
- $responseDoc = new \DomDocument();
- $responseDoc->loadXML($responseXml);
- $errors = $responseDoc->getElementsByTagName('Errors');
- if ($errors->length == 0) {
- $responses = $responseDoc->getElementsByTagName("UploadSiteHostedPicturesResponse");
- foreach ($responses as $response) {
- $acks = $response->getElementsByTagName("Ack");
- $ack = $acks->item(0)->nodeValue;
- //echo "Ack = $ack <BR />\n"; // Success if successful
- $picturesDatas = $response->getElementsByTagName("SiteHostedPictureDetails");
- //$array = iterator_to_array($picturesDatas);
- foreach ($picturesDatas as $picturesData) {
- $fullurls = $picturesData->getElementsByTagName("FullURL");
- //$fullurl[] = $fullurls->item(0)->nodeValue;
- array_push($fullurl, array($fullurls->item(0)->nodeValue, $pdata_value['label']));
- }
- }
- } else {
- $error = $errors->item(0)->getElementsByTagName('SeverityCode');
- $errorDB = $error->item(0)->nodeValue;
- if ($errors->length > 0 && $errorDB != 'Warning') {
- $code = $errors->item(0)->getElementsByTagName('ErrorCode');
- $shortMsg = $errors->item(0)->getElementsByTagName('ShortMessage');
- $longMsg = $errors->item(0)->getElementsByTagName('LongMessage');
- $codeDB = $code->item(0)->nodeValue;
- $shortMsgDB = (count($shortMsg) > 0) ? str_replace(">", ">", str_replace("<", "<", $shortMsg->item(0)->nodeValue)) : '';
- $longMsgDB = (count($longMsg) > 0) ? str_replace(">", ">", str_replace("<", "<", $longMsg->item(0)->nodeValue)) : '';
- \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' => '']);
- } else {
- $responses = $responseDoc->getElementsByTagName("UploadSiteHostedPicturesResponse");
- foreach ($responses as $response) {
- $acks = $response->getElementsByTagName("Ack");
- $ack = $acks->item(0)->nodeValue;
- //echo "Ack = $ack <BR />\n"; // Success if successful
- $picturesDatas = $response->getElementsByTagName("SiteHostedPictureDetails");
- //$array = iterator_to_array($picturesDatas);
- foreach ($picturesDatas as $picturesData) {
- $fullurls = $picturesData->getElementsByTagName("FullURL");
- //$fullurl[] = $fullurls->item(0)->nodeValue;
- //array_push($fullurl, $fullurls->item(0)->nodeValue);
- array_push($fullurl, array($fullurls->item(0)->nodeValue, $pdata_value['label']));
- }
- }
- }
- }
- }
- }
- }
- } else {
- $no_image_error = "Ebay Require atleat one image for product.
- But Below product have no image.";
- $no_image_error.= "Product ID = $import_product->magento_id
- Product SKU = $import_product->mp_sku";
- \Mail::raw($no_image_error, function ($message) {
- $message->to('[email protected]')->bcc('[email protected]')->subject('Product Have No Images - Ebay Error');
- });
- \Log::channel('ebay')->error('This Product have no images : Product ID -' . $import_product->magento_id . ' Product SKU = ' . $import_product->mp_sku);
- \App\EbayListProduct::where('magento_id', $import_product->magento_id)->update(['product_ebay_status' => '4', 'ebay_status' => 'No Image','cron_error' => '']);
- }
- if (is_array($fullurl) && count($fullurl) > 0) {
- if ($import_product->product_ebay_id != '') {
- if (is_array($checkImageExist) && count($checkImageExist) > 0) {
- $imagesUrl = unserialize($import_product->ebay_image_urls);
- if(empty($imagesUrl))
- {
- $serializedFullUrlArr = serialize($fullurl);
- }
- else
- {
- $serializedFullUrlArr = serialize(array_merge($imagesUrl, $fullurl));
- }
- }
- } else {
- $serializedFullUrlArr = serialize($fullurl);
- }
- \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]);
- if ($cronExist) {
- $endDate = date('Y-m-d H:i:s');
- callChannel($startDate, $endDate, $cronExist->id, 'ebay');
- }
- \Log::channel('ebay')->info('Ebay Import Image script run successfully.');
- }
- if ((is_array($emptyArr) && count($emptyArr) > 0) && ($import_product->product_ebay_id != '')) {
- \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]);
- }
- }
- }
- catch(\Exception $e) {
- $designerDetials = \App\Designer::where('designer_id', $import_product->designer_id)->first();
- $designerSettings = \App\Setting::where('designer_id', $import_product->designer_id)->first();
- \App\EbayListProduct::where('magento_id', $import_product->magento_id)->update(['cron_error' => $e->getMessage() ]);
- $cron_error = "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";
- \Mail::raw($cron_error, function ($message) {
- ->subject('Ebay Import Images Cron Error');
- });
- app('db')->rollback();
- \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);
- }
- } // import products loop ends
- }
- }
- public function array_msort($array, $cols) {
- $colarr = array();
- foreach ($cols as $col => $order) {
- $colarr[$col] = array();
- foreach ($array as $k => $row) {
- $colarr[$col]['_' . $k] = strtolower($row[$col]);
- }
- }
- $eval = 'array_multisort(';
- foreach ($cols as $col => $order) {
- $eval.= '$colarr[\'' . $col . '\'],' . $order . ',';
- }
- $eval = substr($eval, 0, -1) . ');';
- eval($eval);
- $ret = array();
- foreach ($colarr as $col => $arr) {
- foreach ($arr as $k => $v) {
- $k = substr($k, 1);
- if (!isset($ret[$k])) $ret[$k] = $array[$k];
- $ret[$k][$col] = $array[$k][$col];
- }
- }
- return $ret;
- }
- public function getRedirectAfterpath($url)
- {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_HEADER, true);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true so that PHP follows any "Location:" header
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- $a = curl_exec($ch); // $a will contain all headers
- $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL
- return $url; // Voila
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment