I am integrating third party API (wordpress) in magento on observer.
Integration working fine on my local system, but when I deploy it on server it give me error like below:
Cannot send headers; headers already sent
2020-07-22T08:58:58+00:00 ERR (3):
exception 'Zend_Controller_Response_Exception' with message 'Cannot send headers; headers already sent in /var/www/html/app/code/local/Custom/Wordpressapi/Model/Observer.php, line 182' in /var/www/html/lib/Zend/Controller/Response/Abstract.php:344
Stack trace:
#0 /var/www/html/lib/Zend/Controller/Response/Abstract.php(148): Zend_Controller_Response_Abstract->canSendHeaders(true)
#1 /var/www/html/app/code/core/Mage/Core/Controller/Response/Http.php(107): Zend_Controller_Response_Abstract->setRedirect('*/*/', 302)
#2 /var/www/html/app/code/local/Custom/Wordpressapi/Model/Observer.php(277): Mage_Core_Controller_Response_Http->setRedirect('*/*/')
#3 /var/www/html/app/code/core/Mage/Core/Model/App.php(1358): Custom_Wordpressapi_Model_Observer->postProductAsBlog(Object(Varien_Event_Observer))
#4 /var/www/html/app/code/core/Mage/Core/Model/App.php(1337): Mage_Core_Model_App->_callObserverMethod(Object(Sterling_Blogapi_Model_Observer), 'postProductAsBl...', Object(Varien_Event_Observer))
#5 /var/www/html/app/Mage.php(483): Mage_Core_Model_App->dispatchEvent('catalog_product...', Array)
#6 /var/www/html/app/code/core/Mage/Core/Model/Abstract.php(466): Mage::dispatchEvent('catalog_product...', Array)
#7 /var/www/html/app/code/local/Mage/Catalog/Model/Product.php(549): Mage_Core_Model_Abstract->_afterSave()
#8 /var/www/html/app/code/core/Mage/Core/Model/Abstract.php(319): Mage_Catalog_Model_Product->_afterSave()
#9 /var/www/html/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php(554): Mage_Core_Model_Abstract->save()
#10 /var/www/html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_Catalog_ProductController->saveAction()
#11 /var/www/html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('save')
#12 /var/www/html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#13 /var/www/html/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
#14 /var/www/html/app/Mage.php(719): Mage_Core_Model_App->run(Array)
#15 /var/www/html/index.php(94): Mage::run('', 'store')
#16 {main}
Here is the code snippet from my observer file:
<?php
class Custom_Wordpressapi_Model_Observer
{
const WORDPRESS_BLOG_API_URL = "wordpresapi/api/api_url";
const WORDPRESS_BLOG_USERNAME = "wordpresapi/api/username";
const WORDPRESS_BLOG_PASSWORD = "wordpresapi/api/password";
public function postProductAsBlog(Varien_Event_Observer $observer)
{
if(Mage::registry('catalog_product_save_after_observer_executed')){
return $this; //this method has already been executed once in this request
}
Mage::register('catalog_product_save_after_observer_executed',true);
if(!Mage::helper('custom_wordpressapi')->isEnable())
{
Mage::getSingleton('adminhtml/session')->addError("Blog api module is disabled, So not able to create/update post on Blog site.");
Mage::app()->getResponse()->setRedirect('*/*/')->sendResponse();
return;
}
$apiUrl = trim(Mage::getStoreConfig(self::WORDPRESS_BLOG_API_URL));
$username = trim(Mage::getStoreConfig(self::WORDPRESS_BLOG_USERNAME));
$password = Mage::helper('core')->decrypt(trim(Mage::getStoreConfig(self::WORDPRESS_BLOG_PASSWORD)));
if($apiUrl == '' && $username == '' && $password == '')
{
Mage::getSingleton('adminhtml/session')->addError("Blog api config information missing, So not able to create/update post on Blog site.");
Mage::app()->getResponse()->setRedirect('*/*/')->sendResponse();
return;
}
/*if(Mage::registry('catalog_product_save_after_observer_executed')){
return $this; //this method has already been executed once in this request
}*/
$product = $observer->getEvent()->getProduct();
$authorization = "Authorization: Basic $username:$password";
$post_id = $id = $name = $title = $conditionType = $condition = $machineUrl = $imgUrl = $capacity = $sku = $shortDesc = $otherInfo = $postContent = $price ='';
$postResponse = $metaInfo = $categories = array();
$updateImage = false;
$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
$attributeSetModel->load($product->getAttributeSetId());
$attributeSetName = $attributeSetModel->getAttributeSetName();
if((!empty($product) && $product->getIsOption() != 1) && $product->getPostToApi() == 1 && ($product->getStatus() == 1 && $product->getIsInStock() == 1) && $attributeSetName == 'Default' )
{
$sku = trim($product->getSku());
$shortDesc = strtoupper(trim($product->getShortDescription()));
$name = trim($product->getName());
$machineUrl = trim(Mage::getBaseUrl().$product->getUrlPath());
$imgUrl =(string)Mage::helper('catalog/image')->init($product, 'image')->resize(500);
$capacity = $product->getResource()->getAttribute('capacity')->getFrontend()->getValue($product);
$condition = trim($product->getCondition());
if($product->getUpdateImage() == 1)
{
$updateImage = true;
}else{
$updateImage = false;
}
if(trim(strtolower($condition)) == '812')
{
$conditionType = ' New';
}
else
{
if(trim(strtolower($condition)) == '814')
{ $conditionType = ' Used'; }
else {$conditionType = '';}
}
$cats = $product->getCategoryIds();
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
$categories[] = $_cat->getName();
}
$metaTitle = trim($product->getMetaTitle());
$metaKeywords = trim($product->getMetaKeyword());
$metaDesc = trim($product->getMetaDescription());
$metaInfo = array('title' =>$metaTitle,'keywords'=>$metaKeywords,'description'=>$metaDesc);
$title = strtoupper(trim($capacity.$conditionType." ".$name." #".$sku));
if(!empty($shortDesc))
{
$postContent .= '<p>'.$shortDesc.'</p>';
}
if($product->getPrice() > 0 && $product->getPrice() != '')
{
$price = Mage::helper('core')->currency($product->getPrice(), true, false);
}
else
{
$price = "Call for price";
}
if($price != '')
{
$postContent .= '<p> Cost: '.$price.'</p>';
}
if(!empty($machineUrl))
{
$postContent .= '<p><a href="'.$machineUrl.'" title="Machine Url">'.$machineUrl.'</a></p>';
}
$postDatas = array(
'title' => $title,
'categories' => $categories,
'machine_url' => $machineUrl,
'short_description' => $shortDesc,
'image_url' => $imgUrl,
'other_info' => $otherInfo,
'blog_post_content' => $postContent,
'meta_info'=>$metaInfo
);
if(Mage::registry('catalog_product_saved_status') == 'old'){
$modelInfo = Mage::getModel('wordpresapi/wordpresapi')->getCollection();
$modelInfo->addFieldToSelect(array('id','blog_id'))->addFieldToFilter('product_sku',array('eq'=>$sku));
$modelData = $modelInfo->getData();
if($modelInfo->count() > 0)
{
$postDatas['post_id'] = $post_id = $modelData[0]['blog_id'];
$postDatas['update_image']= $updateImage;
$id = $modelData[0]['id'];
}
}
try {
$url = $apiUrl;
$curl = new Varien_Http_Adapter_Curl();
$curl->setConfig(array('timeout' => 0));
$headers= array('Content-Type: application/json',$authorization);
$curl->write(Zend_Http_Client::POST, $url, '1.0', $headers, json_encode($postDatas));
$res = $curl->read();
$response = '';
$httpCode = Zend_Http_Response::extractCode($res);
$response = Zend_Http_Response::extractBody($res);
$curl->close();
if ($httpCode == 200) //if success
{
$response = json_decode($response);
if (!empty($response) && is_object($response))
{
if (property_exists($response,'code') && $response->code == 'post_created' || $response->code == 'post_updated') {
if(!empty($response->data) && $response->data != null){
$saveResponse = array();
$product_sku = $blog_id = '';
$update_data = false;
$dataRes = $response->data;
foreach ($dataRes as $k => $data) {
if($k == 'id')
{
$blog_id = $data;
}
if($k == 'date_gmt')
{
$saveResponse['date_created_gmt'] = $data;
}
if($k == 'link')
{
$saveResponse['post_link'] = $data;
}
if($k == 'modified_gmt')
{
$saveResponse['date_updated_gmt'] = $data;
}
if($k == 'categories')
{
$saveResponse['categories'] = (array)$data;
}
$product_sku = $sku;
$update_data = true;
}
if($update_data == true)
{
$infoSet = array('blog_id'=>$blog_id,'product_sku'=>$product_sku,'additional_info'=>null,'other_info'=>serialize($saveResponse));
if($post_id == '')
$model = Mage::getModel('wordpresapi/wordpresapi')->setData($infoSet);
else
{
$infoSet['id'] = $id;
$model = Mage::getModel('wordpresapi/wordpresapi')->load($id);
$model->setData($infoSet);
}
$model->save();
}
}
Mage::log("Success API Msg -- ".$response->message.". For product sku $sku", null, 'blog-api.log', true);
Mage::getSingleton('adminhtml/session')->addSuccess("Blog Post API 0 : ".$response->message);
}
else{
Mage::log("API Msg -- ".$response->message.". For product sku $sku", null, 'blog-api.log', true);
Mage::getSingleton('adminhtml/session')->addError("Blog Post API 1 : ".$response->message);
}
}
else
{
Mage::getSingleton('adminhtml/session')->addError("Blog Post API, Nothing to post. : ".$response->message);
}
}
}catch (Exception $e)
{
Mage::log("Error API Msg -- " . $e->getMessage().". For product sku $sku", null, 'blog-api.log', true);
}
Mage::app()->getResponse()->setRedirect('*/*/')->sendResponse();
}
else{
Mage::app()->getResponse()->setRedirect('*/*/')->sendResponse();
}
return;
}
public function postProductData(Varien_Event_Observer $observer)
{
if(Mage::helper('custom_wordpressapi')->isModuleEnabled()) {
$product = $observer->getEvent()->getProduct();
Mage::unregister('catalog_product_saved_status');
if ($product->isObjectNew()) {
Mage::register('catalog_product_saved_status', "new");
} else {
Mage::register('catalog_product_saved_status', "old");
}
}
}
}