<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title />
	
	<link>http://www.excellencemagentoblog.com</link>
	<description />
	<lastBuildDate>Fri, 15 Feb 2013 08:04:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/etech-blog" /><feedburner:info uri="etech-blog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><creativeCommons:license>http://creativecommons.org/licenses/by-nc-nd/2.0/</creativeCommons:license><item>
		<title>Coming Soon …. Magento 2</title>
		<link>http://feedproxy.google.com/~r/etech-blog/~3/F6zgRTo3zPs/coming-soon-magento-2</link>
		<comments>http://www.excellencemagentoblog.com/coming-soon-magento-2#comments</comments>
		<pubDate>Thu, 14 Feb 2013 11:33:34 +0000</pubDate>
		<dc:creator>Manish Prakash</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[magento2]]></category>

		<guid isPermaLink="false">http://www.excellencemagentoblog.com/?p=3088</guid>
		<description><![CDATA[After success of Magento 1.x, Magento Team in a process &#8230; <a href="http://www.excellencemagentoblog.com/coming-soon-magento-2"> <span class="meta-nav"></span></a>]]></description>
			<content:encoded><![CDATA[<div class="intro">After success of Magento 1.x, Magento Team in a process of developing Magento 2.</div>
<p>Magento 2 is an open source eCommerce R&amp;D project facilitating the improvement of Magento Core products.<br />
With the new and improved features in Magento 2, developers will be able to offer more functionality to merchants and continue to grow with the platform. <br />
Magento 2 is a prospective future version of the Magento e-commerce software, currently still in the development stage.<br />
This is the first of many posts in the next few months that will provide further insight and updates about the progress, process, technical architecture <br />
and strategy as well as many other facets that involve this important project and milestone for the Magento community.<br />
<span id="more-3088"></span></p>
<h2>Some of Features That  Magento 2 Offers</h2>
<p>•	Magento 2.0 will run on PHP 5.3 and Zend Framework as 1.0. And it will support MSSQL, Oracle and some other database as well.  This is a good news for Windows Platform Server. We can see that Magento keep growing and seek to support more and more popular platform soon.<br />
•	Performance is always an issue for Magento so it is recognized as resource hungry and not efficient.  The team of Magento keep improving the performance of Magento version by version. With the 2.0, the performance of Magento will be at least 20% more faster than the latest Magento 1.x versions. <br />
•	Magento 2.0 uses jQuery library as its default JavaScript library. It&#8217;s a big plus for those who want to get rid of prototype and jquery conflict.<br />
•	The modules like catalog, customer, checkout, CMS, sales, etc will be components with high code coupling between each other. Now if you don’t want to use a certain module, you can simply disable it and write your own one.<br /> <br />
•	Magento uses Zend Framework but you can’t get this information easily as the directories structure of Magento 1.x series are quite different from the Zend Framework. For Magento 2.0, the directories structures will be quite similar to the Zend Framework. This is very Exciting for theme development as things like Layout Templates, CSS, Images, JavaScript become more modular. You can manage all of them within a module folder.<br />
Here is screenshot for Directory structure and Module Structure of Magento 2 <a href="http://www.excellencemagentoblog.com/wp-content/uploads/2013/02/New-Picture.bmp"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/08/screen-e1315502200795.png" alt="jQuery Folder Structure" width="12" height="16" /></a> and <a href="http://www.excellencemagentoblog.com/wp-content/uploads/2013/02/mod-structure.bmp"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/08/screen-e1315502200795.png" alt="jQuery Folder Structure" width="12" height="16" /></a><br />
<br />
•	Previously Magento 1.x using module.xml file @ app/etc/modules/ to activate our module but in Magento2 it has been changed. Now we will use config.xml file to activate our module means adding active and codePool tags into your config.xml. Like: </p>
<pre class="brush: xml; title: ; notranslate">
&lt;config&gt;
    &lt;modules&gt;
        &lt;Mage_Catalog&gt;
            &lt;version&gt;1.6.0.0.20&lt;/version&gt;
            &lt;active&gt;true&lt;/active&gt;
            &lt;codePool&gt;core&lt;/codePool&gt;
        &lt;/Mage_Catalog&gt;
    &lt;/modules&gt;
.....
</pre>
<p>In  Magento2 , factory method has been removed .The way you call models, helpers, blocks is fully different in Magento2 .Instead of factory names you need to use the full class name now as : </p>
<p>=&gt;Mage::helper(&#8216;Mage_Catalog_Helper_Product_View&#8217;)<br />
=&gt;Mage::getModel(&#8216;Mage_Catalog_Model_Category&#8217;)<br />
=&gt; Mage::getSingleton(&#8216;Mage_Catalog_Model_Session&#8217;)</p>
<p>And Change in layout xml  is introduced in Magento 2. Each module has it’s own layout.xml in module view folder. And Block type uses Class name of block instead of class alias as : </p>
<pre class="brush: xml; title: ; notranslate">
&lt;block type=&quot;Mage_Catalog_Block_Product_Compare_Sidebar&quot; before=&quot;cart_sidebar&quot; name=&quot;catalog.compare.sidebar&quot; template=&quot;product/compare/sidebar.phtml&quot;/&gt;
            &lt;block type=&quot;Mage_Core_Block_Template&quot; name=&quot;right.permanent.callout&quot; template=&quot;Mage_Page::callouts/right_col.phtml&quot;&gt;
                &lt;action method=&quot;setImgSrc&quot;&gt;&lt;src&gt;Mage_Catalog::images/media/col_right_callout.jpg&lt;/src&gt;&lt;/action&gt;
                &lt;action method=&quot;setImgAlt&quot; translate=&quot;alt&quot; module=&quot;Mage_Catalog&quot;&gt;&lt;alt&gt;Keep your eyes open for our special Back to School items and save A LOT!&lt;/alt&gt;&lt;/action&gt;
            &lt;/block&gt;

</pre>
<h2>In Admin Magento 2 have some major changes:</h2>
<p>
•	Introduction of  Visual design editor. <a href="http://www.excellencemagentoblog.com/wp-content/uploads/2013/02/VDE.bmp"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/08/screen-e1315502200795.png" alt="jQuery Folder Structure" width="12" height="16" /></a>.<br />
The Visual Design Editor is an easy to use, “drag and drop” interface for editing Magento Page Layout. Implementation of the Visual Design Editor means that modifying the arrangement/configuration of Containers and Blocks no longer requires specialized technical knowledge; many of these changes can be made easily in the Admin Panel by any site administrator.<br />
The Visual Design Editor represents website pages and page types as collections of block elements: Blocks and Containers. <br />
•	All-new look &amp; feel of backend UI &#8212; &#8220;Magento 2 backend&#8221; theme.</p>
<h2>Block: </h2>
<p>A block is a block-level HTML element on a page, which can be manipulated by the visual design editor. Regardless of whether the element has content or not, the design editor visually distinguishes it from other elements and provides necessary controls for manipulating it. In future: A block cannot contain other blocks.</p>
<h2>Container:</h2>
<p>A container, like a block, is a block-level HTML element which is visually distinguished and can be manipulated by the design editor. Containers don’t have own content, but consist of other blocks or containers. Containers represent area for “dropping”. Container stores information about sort order for elements within.</p>
<p>•	Removal of  Category Tree from Create Product Page in Admin, Addition of Drag – n – Drop Product image feature , Change Attribute set while  creating and editing of Product. <a href="http://www.excellencemagentoblog.com/wp-content/uploads/2013/02/mage2backend2.bmp"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/08/screen-e1315502200795.png" alt="jQuery Folder Structure" width="12" height="16" /></a>.</p>
<img src="http://feeds.feedburner.com/~r/etech-blog/~4/F6zgRTo3zPs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.excellencemagentoblog.com/coming-soon-magento-2/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		<feedburner:origLink>http://www.excellencemagentoblog.com/coming-soon-magento-2?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=coming-soon-magento-2</feedburner:origLink></item>
		<item>
		<title>How to hide price from non-logged in users / guest users.</title>
		<link>http://feedproxy.google.com/~r/etech-blog/~3/blsmFVbeCek/how-to-hide-price-from-non-logged-in-users-guest-users</link>
		<comments>http://www.excellencemagentoblog.com/how-to-hide-price-from-non-logged-in-users-guest-users#comments</comments>
		<pubDate>Thu, 14 Feb 2013 11:31:20 +0000</pubDate>
		<dc:creator>Manish Prakash</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Magento]]></category>

		<guid isPermaLink="false">http://www.excellencemagentoblog.com/?p=3120</guid>
		<description><![CDATA[In this blog post, we will see how to hide &#8230; <a href="http://www.excellencemagentoblog.com/how-to-hide-price-from-non-logged-in-users-guest-users"> <span class="meta-nav"></span></a>]]></description>
			<content:encoded><![CDATA[<div class="intro">In this blog post, we will see how to hide price from non-logged in users / guest users.</div>
<p>Many a times in an ecommerce website, we do not wish the guest users to know the price of the catalog products. The solution to this problem is rather easy. What we just need to do is first of all figure out where the product prices are shown. Then hide them from guest users.<br />
<span id="more-3120"></span><br />
Attached is the source files of magento module created.<br />
<div class='facebook-download'>
<table border="0" cellpadding="3" width="80%" class='noauth'>
  <tr>
    <td width="10%" style="text-align:center" valign='top'  class='image'>
      <img src="http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/fb_nouser.jpg" alt="#twitter#" width="48px" height="48px">
    </td>
    <td width="60%" valign='top' style='padding-top: 13px !important;'>
    	<b>Download: </b><span class='name'>Hide Price</span><small>(17.28KB)</small>
    	<span style="padding-left:20px"><b>Clicks: </b>57</span>
    	<br />
      	Login via <a onclick='login();return false;' href='#'>facebook</a> to download the file!
      	<br/>
      	<div style='float:left'>
      	<a onclick='login();return false;' href='#'><img src='http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/facebook_login.jpg' alt='facebook login'/></a>
      	</div>
      	<div style='float:left;margin-top: 3px;margin-left: 6px;'>
      	<small>By logging in you agree to subscribe to our montly newsletter as well.</small>
      	</div>
      	<div style='clear:both'></div>
      </td>
  </tr>
</table>
</div><br />
While we are at it we will also hide the ‘Add to Cart’ buttons everywhere (for guest users).  There is no point in hiding the price everywhere and then allowing them to add product to the cart.<br />
In magento by default price is shown on following places<br />
•	Category list page (where all the product of a category are listed).<br />
•	Product view page (where product details are shown).<br />
•	Compare pop up (where two or more products are compared side by side).</p>
<p>Override the default magento files.<br />
Since in this case we only need to override view files (phtml). We need only a very basic module. For module development refer to module development series.<br />
Price on various places is shown from price.phtml which is located at ‘/app/design/frontend/base/default/template/catalog/product/price.phtml’.</p>
<h2>To override this we need to add the following code in default tags of our frontend layout file.</h2>
<pre class="brush: xml; title: ; notranslate">
&lt;default&gt;
        &lt;reference name=&quot;catalog_product_price_template&quot;&gt;
        	&lt;action method=&quot;addPriceBlockType&quot;&gt;&lt;type&gt;simple&lt;/type&gt;&lt;block&gt;catalog/product_price&lt;/block&gt;&lt;template&gt;hideprice/price.phtml&lt;/template&gt;&lt;/action&gt;
        	&lt;action method=&quot;addPriceBlockType&quot;&gt;&lt;type&gt;grouped&lt;/type&gt;&lt;block&gt;catalog/product_price&lt;/block&gt;&lt;template&gt;hideprice/price.phtml&lt;/template&gt;&lt;/action&gt;
        	&lt;action method=&quot;addPriceBlockType&quot;&gt;&lt;type&gt;configurable&lt;/type&gt;&lt;block&gt;catalog/product_price&lt;/block&gt;&lt;template&gt;hideprice/price.phtml&lt;/template&gt;&lt;/action&gt;
        	&lt;action method=&quot;addPriceBlockType&quot;&gt;&lt;type&gt;virtual&lt;/type&gt;&lt;block&gt;catalog/product_price&lt;/block&gt;&lt;template&gt;hideprice/price.phtml&lt;/template&gt;&lt;/action&gt;
        	&lt;action method=&quot;addPriceBlockType&quot;&gt;&lt;type&gt;bundled&lt;/type&gt;&lt;block&gt;catalog/product_price&lt;/block&gt;&lt;template&gt;hideprice/price.phtml&lt;/template&gt;&lt;/action&gt;
        &lt;/reference&gt;
 &lt;/default&gt;
</pre>
<p>Then copy the default ‘price.phtml’ and place it in the specified location (in our case ‘hideprice/price.phtml’).  And the place the following code on top of it.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php 
if(!Mage::getSingleton('customer/session')-&gt;isLoggedIn()){
	echo '&lt;span class=&quot;login_for_price&quot;&gt;&lt;b&gt;Login to See Price&lt;/b&gt;&lt;/span&gt;&lt;br&gt;';
	return;
}
?&gt;
</pre>
<p> This basically hides price for guest users everywhere (since we used override in default tags).<br />
 Now to hide the ‘Add to Cart’ button on category list page. Use the following code to override the default ‘/app/design/frontend/base/default/template/catalog/product/list.phtml’. Add this to your module’s layout file.<br />
For default </p>
<pre class="brush: xml; title: ; notranslate">
&lt;catalog_category_default&gt;
         &lt;reference name=&quot;product_list&quot;&gt;
             &lt;action method=&quot;setTemplate&quot;&gt;&lt;template&gt;hideprice/list.phtml&lt;/template&gt;&lt;/action&gt;
         &lt;/reference&gt;
&lt;/catalog_category_default&gt;
And for layered navigation
&lt;catalog_category_layered&gt;
         &lt;reference name=&quot;product_list&quot;&gt;
             &lt;action method=&quot;setTemplate&quot;&gt;&lt;template&gt;hideprice/list.phtml&lt;/template&gt;&lt;/action&gt;
         &lt;/reference&gt;
&lt;/catalog_category_layered&gt;
</pre>
<p>Now copy the default ‘list.phtml’ to your module. Replace the following code (around line number-109)</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php if($_product-&gt;isSaleable()): ?&gt;
                        &lt;button type=&quot;button&quot; title=&quot;&lt;?php echo $this-&gt;__('Add to Cart') ?&gt;&quot; class=&quot;button btn-cart&quot; onclick=&quot;setLocation('&lt;?php echo $this-&gt;getAddToCartUrl($_product) ?&gt;')&quot;&gt;&lt;span&gt;&lt;span&gt;&lt;?php echo $this-&gt;__('Add to Cart') ?&gt;&lt;/span&gt;&lt;/span&gt;&lt;/button&gt;
                    &lt;?php else: ?&gt;
                        &lt;p class=&quot;availability out-of-stock&quot;&gt;&lt;span&gt;&lt;?php echo $this-&gt;__('Out of stock') ?&gt;&lt;/span&gt;&lt;/p&gt;
&lt;?php endif; ?&gt;
</pre>
<p>With  this.</p>
<pre class="brush: php; title: ; notranslate">
                &lt;?php 
                    	if(!Mage::getSingleton('customer/session')-&gt;isLoggedIn()){
	                    	echo '&lt;span class=&quot;login_for_details&quot; style=&quot;float:left&quot;&gt;&lt;b&gt;Login to Add to Cart&lt;/b&gt;&lt;/span&gt;';
	                    	}
	                    	else{
                    ?&gt;
                    &lt;?php if($_product-&gt;isSaleable()): ?&gt;
                        &lt;button type=&quot;button&quot; title=&quot;&lt;?php echo $this-&gt;__('Add to Cart') ?&gt;&quot; class=&quot;button btn-cart&quot; onclick=&quot;setLocation('&lt;?php echo $this-&gt;getAddToCartUrl($_product) ?&gt;')&quot;&gt;&lt;span&gt;&lt;span&gt;&lt;?php echo $this-&gt;__('Add to Cart') ?&gt;&lt;/span&gt;&lt;/span&gt;&lt;/button&gt;
                    &lt;?php else: ?&gt;
                        &lt;p class=&quot;availability out-of-stock&quot;&gt;&lt;span&gt;&lt;?php echo $this-&gt;__('Out of stock') ?&gt;&lt;/span&gt;&lt;/p&gt;
                    &lt;?php endif; ?&gt;
                    &lt;?php 	}?&gt;
</pre>
<p>In the above code we just check if the user is logged in. If yes the code runs normally like the default else we display a message accordingly.<br />
Now to hide the ‘Add to Cart’ button on product detail page. Use the following code to override the default ‘/app/design/frontend/base/default/template/catalog/product/view/addtocart.phtml’. Add this to your modules layout file.</p>
<pre class="brush: xml; title: ; notranslate">
     &lt;catalog_product_view&gt;
         &lt;reference name=&quot;product.info.addtocart&quot;&gt;
     	    &lt;action method=&quot;setTemplate&quot;&gt;&lt;template&gt;hideprice/addtocart.phtml&lt;/template&gt;&lt;/action&gt;
     	&lt;/reference&gt;
     &lt;/catalog_product_view&gt;
</pre>
<p>Then copy the default ‘addtocart.phtml’ to your module and add the following code on top of it.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php 
if(!Mage::getSingleton('customer/session')-&gt;isLoggedIn()){
	echo '&lt;span class=&quot;login_for_details&quot; style=&quot;float:left&quot;&gt;&lt;b&gt;Login to Add to Cart&lt;/b&gt;&lt;/span&gt;';
	return;
}
?&gt;
</pre>
<p>Similarly to hide the ‘Add to Cart’ on compare page. Default page is at ‘/app/design/frontend/base/default/template/catalog/product/compare/list.phtml’. We use following code in our module’s layout xml file.</p>
<pre class="brush: xml; title: ; notranslate">
     &lt;catalog_product_compare_index&gt;
         &lt;reference name=&quot;catalog.compare.list&quot;&gt;
             &lt;action method=&quot;setTemplate&quot;&gt;&lt;template&gt;hideprice/compare/list.phtml&lt;/template&gt;&lt;/action&gt;
         &lt;/reference&gt;
     &lt;/catalog_product_compare_index&gt;
</pre>
<p>Then copy the default ‘compare/list.phtml’.  look for the following code, it is found in two places line numbers (67 &amp; 118) </p>
<pre class="brush: php; title: ; notranslate">
                    &lt;?php if($_item-&gt;isSaleable()): ?&gt;
                        &lt;p&gt;&lt;button type=&quot;button&quot; title=&quot;&lt;?php echo $this-&gt;__('Add to Cart') ?&gt;&quot; class=&quot;button btn-cart&quot; onclick=&quot;setPLocation('&lt;?php echo $this-&gt;helper('catalog/product_compare')-&gt;getAddToCartUrl($_item) ?&gt;', true)&quot;&gt;&lt;span&gt;&lt;span&gt;&lt;?php echo $this-&gt;__('Add to Cart') ?&gt;&lt;/span&gt;&lt;/span&gt;&lt;/button&gt;&lt;/p&gt;
                    &lt;?php else: ?&gt;
                        &lt;p class=&quot;availability out-of-stock&quot;&gt;&lt;span&gt;&lt;?php echo $this-&gt;__('Out of stock') ?&gt;&lt;/span&gt;&lt;/p&gt;
                    &lt;?php endif; ?&gt;
</pre>
<p>Replace it with </p>
<pre class="brush: php; title: ; notranslate">
                &lt;?php 
                    	if(!Mage::getSingleton('customer/session')-&gt;isLoggedIn()){
	                    	echo '&lt;span class=&quot;login_for_details&quot; style=&quot;float:left&quot;&gt;&lt;b&gt;Login to Add to Cart&lt;/b&gt;&lt;/span&gt;';
	                    	}
	                    	else{
                    ?&gt;
                    &lt;?php if($_product-&gt;isSaleable()): ?&gt;
                        &lt;button type=&quot;button&quot; title=&quot;&lt;?php echo $this-&gt;__('Add to Cart') ?&gt;&quot; class=&quot;button btn-cart&quot; onclick=&quot;setLocation('&lt;?php echo $this-&gt;getAddToCartUrl($_product) ?&gt;')&quot;&gt;&lt;span&gt;&lt;span&gt;&lt;?php echo $this-&gt;__('Add to Cart') ?&gt;&lt;/span&gt;&lt;/span&gt;&lt;/button&gt;
                    &lt;?php else: ?&gt;
                        &lt;p class=&quot;availability out-of-stock&quot;&gt;&lt;span&gt;&lt;?php echo $this-&gt;__('Out of stock') ?&gt;&lt;/span&gt;&lt;/p&gt;
                    &lt;?php endif; ?&gt;
                    &lt;?php 	}?&gt;
</pre>
<h2>Another Way to Hide Price for Not Logged in User (Using Event to Set Price Equals to Zero) : </h2>
<p>To do this We use two events :- </p>
<pre class="brush: xml; title: ; notranslate">
 &lt;catalog_product_get_final_price&gt;
	        &lt;observers&gt;
	          &lt;hideprice_catalog_price_observer&gt;
	            &lt;type&gt;singleton&lt;/type&gt;
	            &lt;class&gt;Wsc_Postcode_Model_Observer&lt;/class&gt;
	            &lt;method&gt;hidePrice&lt;/method&gt;
	          &lt;/hideprice_catalog_price_observer&gt;
	        &lt;/observers&gt;
	      &lt;/catalog_product_get_final_price&gt;
</pre>
<p>And,</p>
<pre class="brush: xml; title: ; notranslate">     
	       &lt;catalog_product_collection_load_after&gt;
	        &lt;observers&gt;
	          &lt;hprice_catalog_price_observer&gt;
	            &lt;type&gt;singleton&lt;/type&gt;
	            &lt;class&gt;Wsc_Postcode_Model_Observer&lt;/class&gt;
	            &lt;method&gt;hidePriceCatalog&lt;/method&gt;
	          &lt;/hprice_catalog_price_observer&gt;
	        &lt;/observers&gt;
	      &lt;/catalog_product_collection_load_after&gt;
</pre>
<p>=&gt; catalog_product_get_final_price event is used to set final price equal to zero on product while catalog_product_collection_load_after event is used to set final price on catalog page.</p>
<p>And after that we simply check if user is not logged in (Observer.php) and set final price equals to zero</p>
<pre class="brush: php; title: ; notranslate">
public function hidePrice($observer){
            $event = $observer-&gt;getEvent();
            $product = $event-&gt;getProduct(); 
            if(!Mage::getSingleton('customer/session')-&gt;isLoggedIn()){
            	$product-&gt;setFinalPrice(0);
    			$product-&gt;setPrice(0);
            }
            
    }
    
    public function hidePriceCatalog($observer){
    	$products = $observer-&gt;getCollection();
    
    	if(!Mage::getSingleton('customer/session')-&gt;isLoggedIn()){
    		foreach( $products as $product )
    		{
    			$product-&gt;setFinalPrice(0);
    			$product-&gt;setPrice(0);
    		}
    	}
    }
</pre>
<p>And on phtml we can also check :</p>
<pre class="brush: php; title: ; notranslate">
 if($_product-&gt;getFinalPrice() == 0 || $_product-&gt;getPrice() == 0){
    	echo '&lt;span class=&quot;login_for_price&quot;&gt;&lt;b&gt;Login to See Price&lt;/b&gt;&lt;br&gt;&lt;/span&gt;';
    	return;
    }
</pre>
<p>That’s all that is required to hide the ‘price’ and ‘add to cart’ button on most of the pages. This is just a basic customization it can be further enhanced to hide other details as well as to hide details from other group of users.</p>
<img src="http://feeds.feedburner.com/~r/etech-blog/~4/blsmFVbeCek" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.excellencemagentoblog.com/how-to-hide-price-from-non-logged-in-users-guest-users/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://www.excellencemagentoblog.com/how-to-hide-price-from-non-logged-in-users-guest-users?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=how-to-hide-price-from-non-logged-in-users-guest-users</feedburner:origLink></item>
		<item>
		<title>Add wysiwyg editor in Magento Custom Module</title>
		<link>http://feedproxy.google.com/~r/etech-blog/~3/li97mKDXY7A/add-wysiwyg-editor-in-magento-custom-module</link>
		<comments>http://www.excellencemagentoblog.com/add-wysiwyg-editor-in-magento-custom-module#comments</comments>
		<pubDate>Thu, 14 Feb 2013 11:31:00 +0000</pubDate>
		<dc:creator>Manish Prakash</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Magento]]></category>

		<guid isPermaLink="false">http://www.excellencemagentoblog.com/?p=1199</guid>
		<description><![CDATA[In this blog post, we will see how to add &#8230; <a href="http://www.excellencemagentoblog.com/add-wysiwyg-editor-in-magento-custom-module"> <span class="meta-nav"></span></a>]]></description>
			<content:encoded><![CDATA[<div class="intro">In this blog post, we will see how to add wysiwyg editor in magento admin forms.</div>
<p>This is very and well known problem for every magento developer. So here is a simple solution for this problem Step by step explained.<br />
We need create a magento module for this purpose, but it is not necessary.<br />
<span id="more-1199"></span><br />
Attached is the source files of magento module created.<br />
<div class='facebook-download'>
<table border="0" cellpadding="3" width="80%" class='noauth'>
  <tr>
    <td width="10%" style="text-align:center" valign='top'  class='image'>
      <img src="http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/fb_nouser.jpg" alt="#twitter#" width="48px" height="48px">
    </td>
    <td width="60%" valign='top' style='padding-top: 13px !important;'>
    	<b>Download: </b><span class='name'>wysiwyg editor module</span><small>(21.10KB)</small>
    	<span style="padding-left:20px"><b>Clicks: </b>37</span>
    	<br />
      	Login via <a onclick='login();return false;' href='#'>facebook</a> to download the file!
      	<br/>
      	<div style='float:left'>
      	<a onclick='login();return false;' href='#'><img src='http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/facebook_login.jpg' alt='facebook login'/></a>
      	</div>
      	<div style='float:left;margin-top: 3px;margin-left: 6px;'>
      	<small>By logging in you agree to subscribe to our montly newsletter as well.</small>
      	</div>
      	<div style='clear:both'></div>
      </td>
  </tr>
</table>
</div><br />
So lets start of. </p>
<h2>Step 1: Add necessary js and css files for wysiwyg editor in your module </h2>
<p>Add necessary js and css files in app/design/frontend/default/default/layout/editor.xml</p>
<pre class="brush: xml; title: ; notranslate">
&lt;default&gt; 
			&lt;reference name=&quot;head&quot;&gt; 
			&lt;action method=&quot;setCanLoadExtJs&quot;&gt;&lt;flag&gt;1&lt;/flag&gt;&lt;/action&gt; 
			&lt;action method=&quot;setCanLoadTinyMce&quot;&gt;&lt;flag&gt;1&lt;/flag&gt;&lt;/action&gt;
			&lt;action method=&quot;addJs&quot;&gt;&lt;script&gt;mage/adminhtml/variables.js&lt;/script&gt;&lt;/action&gt; 
			&lt;action method=&quot;addJs&quot;&gt;&lt;script&gt;mage/adminhtml/wysiwyg/widget.js&lt;/script&gt;&lt;/action&gt; 
			&lt;action method=&quot;addJs&quot;&gt;&lt;script&gt;lib/flex.js&lt;/script&gt;&lt;/action&gt; 
			&lt;action method=&quot;addJs&quot;&gt;&lt;script&gt;lib/FABridge.js&lt;/script&gt;&lt;/action&gt; 
			&lt;action method=&quot;addJs&quot;&gt;&lt;script&gt;mage/adminhtml/flexuploader.js&lt;/script&gt;&lt;/action&gt; 
			&lt;action method=&quot;addJs&quot;&gt;&lt;script&gt;mage/adminhtml/browser.js&lt;/script&gt;&lt;/action&gt; 
			&lt;action method=&quot;addJs&quot;&gt;&lt;script&gt;prototype/window.js&lt;/script&gt;&lt;/action&gt;
			&lt;action method=&quot;addJs&quot;&gt;&lt;script&gt;prototype/prototype.js&lt;/script&gt;&lt;/action&gt; 
			&lt;action method=&quot;addItem&quot;&gt;&lt;type&gt;js_css&lt;/type&gt;&lt;name&gt;prototype/windows/themes/default.css&lt;/name&gt;&lt;/action&gt; 
			&lt;action method=&quot;addItem&quot;&gt;&lt;type&gt;js_css&lt;/type&gt;&lt;name&gt;prototype/windows/themes/magento.css&lt;/name&gt;&lt;/action&gt;
			&lt;/reference&gt; 
	&lt;/default&gt;

</pre>
<h2>Step 2: Code to create wysiwyg editor</h2>
<p>Go to [app/code/local/YOUR_NAMESPACE/MODULE_NAME/block/Adminhtml/Editor/Edit/Tab/Form.php] and under your _prepareLayout() function add this code</p>
<pre class="brush: php; title: ; notranslate">
protected function _prepareLayout()
	{
		$return = parent::_prepareLayout();
		if (Mage::getSingleton('cms/wysiwyg_config')-&gt;isEnabled()) {
			$this-&gt;getLayout()-&gt;getBlock('head')-&gt;setCanLoadTinyMce(true);
		}
		return $return;
	}
</pre>
<p>Now in your _prepareForm() function add this code to create wysiwyg editor</p>
<pre class="brush: php; title: ; notranslate">
protected function _prepareForm()
{
---

$fieldset-&gt;addField('contents', 'editor', 
                		array (
                        'name' =&gt; 'contents', 
                        'label' =&gt; Mage::helper('editor')-&gt;__('Content'), 
                        'title' =&gt; Mage::helper('editor')-&gt;__('Content'), 
                        'style' =&gt; 'height:36em;',
                        'config'    =&gt; Mage::getSingleton('cms/wysiwyg_config')-&gt;getConfig(),
                        'required' =&gt; true ));

				---
				}

</pre>
<p>That’s it this will create a wysiwyg editor in your admin custom module.<br />
Now let us see the explanation of the above code</p>
<pre class="brush: php; title: ; notranslate">
$return = parent::_prepareLayout();
		if (Mage::getSingleton('cms/wysiwyg_config')-&gt;isEnabled()) {
			$this-&gt;getLayout()-&gt;getBlock('head')-&gt;setCanLoadTinyMce(true);
		}
		return $return;
</pre>
<p>this code will check if the wysiwyg is enabled in admin if enabled then it will load the TinyMice Js.</p>
<pre class="brush: php; title: ; notranslate">
$fieldset-&gt;addField('contents', 'editor', 
                		array (
                        'name' =&gt; 'contents', 
                        'label' =&gt; Mage::helper('editor')-&gt;__('Content'), 
                        'title' =&gt; Mage::helper('editor')-&gt;__('Content'), 
                        'style' =&gt; 'height:36em;',
                        'config'    =&gt; Mage::getSingleton('cms/wysiwyg_config')-&gt;getConfig(),
                        'required' =&gt; true ));
</pre>
<p>From this code the editor is been created. In this in the first line it is telling to add a field of type editor which has name contents .<br />
The line &#8216;config&#8217;    =&gt; Mage::getSingleton(&#8216;cms/wysiwyg_config&#8217;)-&gt;getConfig(),</p>
<p>will load the config for wysiwyg editor and your editor will be created.<br />
But it will not work for now. To make it work you need to make some changes. You need to rewrite your module’s adminurl to make your wysiwyg editor work.</p>
<h2>Step 3: Rewriting our module admin url in config.xml</h2>
<p>So first we need to create module which will create forms in admin as we have described In our “Admin Module Development”.<br />
Now in your module’s config.xml Replace the admin route with an injection of your module into the existing adminhtml route. <br />
app/code/local/Excllence/Editor/etc/config.xml </p>
<pre class="brush: xml; title: ; notranslate">
&lt;admin&gt;
    &lt;routers&gt;
        &lt;editor&gt;
            &lt;use&gt;admin&lt;/use&gt;
            &lt;args&gt;
                &lt;module&gt; Excellence_Editor &lt;/module&gt;
                &lt;frontName&gt;editor&lt;/frontName&gt;
            &lt;/args&gt;
        &lt;/editor&gt;
    &lt;/routers&gt;
&lt;/admin&gt;
</pre>
<p>Becomes:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;admin&gt;
        &lt;routers&gt;
            &lt;adminhtml&gt;
                &lt;args&gt;
                    &lt;modules&gt;
                        &lt;Excellence_Editor_Adminhtml before=&quot;Mage_Adminhtml&quot;&gt;Excellence_Editor_Adminhtml&lt;/Excellence_Editor_Adminhtml&gt;
                    &lt;/modules&gt;
                &lt;/args&gt;
            &lt;/adminhtml&gt;
        &lt;/routers&gt;
    &lt;/admin&gt;
</pre>
<p>And:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;adminhtml&gt;
    &lt;menu&gt;
        &lt;editor module=&quot; editor &quot;&gt;
             &lt;title&gt;Editor&lt;/title&gt;
             &lt;sort_order&gt;99&lt;/sort_order&gt;
             &lt;children&gt;
                 &lt;add module=&quot; editor &quot;&gt;
                     &lt;title&gt;Manage Items&lt;/title&gt;
                     &lt;sort_order&gt;0&lt;/sort_order&gt;
                     &lt;action&gt;editor/adminhtml_editor&lt;/action&gt;
                &lt;/add&gt;
                ...
            &lt;/children&gt;
        &lt;/editor&gt;
    &lt;/menu&gt;
&lt;/adminhtml&gt;
</pre>
<p>Becomes:</p>
<pre class="brush: xml; title: ; notranslate">
  &lt;adminhtml&gt;       
        &lt;menu&gt;
			&lt;editor module=&quot;editor&quot;&gt;
				&lt;title&gt;Editor&lt;/title&gt;
				&lt;sort_order&gt;99&lt;/sort_order&gt;               
				&lt;children&gt;
					&lt;items module=&quot;editor&quot;&gt;
						&lt;title&gt;Manage Items&lt;/title&gt;
						&lt;sort_order&gt;0&lt;/sort_order&gt;
						&lt;action&gt;adminhtml/editor/&lt;/action&gt;
					&lt;/items&gt;
				&lt;/children&gt;
			&lt;/editor&gt;
        &lt;/menu&gt;        

	 ---        
    &lt;/adminhtml&gt;
</pre>
<h2>Step 4: Rewriting our module admin url in editor.xml</h2>
<p>And in app/design/frontend/default/default/layout/editor.xml</p>
<pre class="brush: xml; title: ; notranslate">
&lt;editor_adminhtml_editor_index&gt;
    &lt;reference name=&quot;content&quot;&gt;
        &lt;block type=&quot;editor/adminhtml_editor&quot; name=&quot;editor&quot; /&gt;
    &lt;/reference&gt;
&lt;/editor_adminhtml_editor_index &gt;
</pre>
<p>Becomes:</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;adminhtml_editor_index&gt;
        &lt;update handle=&quot;editor_index_index&quot;/&gt;
        &lt;reference name=&quot;content&quot;&gt;
            &lt;block type=&quot;editor/adminhtml_editor&quot; name=&quot;myadmin&quot; /&gt;
        &lt;/reference&gt;
    &lt;/adminhtml_editor_index&gt;
</pre>
<p>Now our admin url rewriting is been done.. <br />
Now our wysiwyg editor will work now.</p>
<img src="http://feeds.feedburner.com/~r/etech-blog/~4/li97mKDXY7A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.excellencemagentoblog.com/add-wysiwyg-editor-in-magento-custom-module/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.excellencemagentoblog.com/add-wysiwyg-editor-in-magento-custom-module?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=add-wysiwyg-editor-in-magento-custom-module</feedburner:origLink></item>
		<item>
		<title>Magento Multiple Website Store – Login</title>
		<link>http://feedproxy.google.com/~r/etech-blog/~3/2h4Rxb5mq0E/magento-multiple-website-login</link>
		<comments>http://www.excellencemagentoblog.com/magento-multiple-website-login#comments</comments>
		<pubDate>Sat, 15 Dec 2012 08:18:51 +0000</pubDate>
		<dc:creator>Manish Prakash</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[multiple domain]]></category>
		<category><![CDATA[multiple website]]></category>

		<guid isPermaLink="false">http://www.excellencemagentoblog.com/?p=3047</guid>
		<description><![CDATA[In this tutorial, we will see how to setup common &#8230; <a href="http://www.excellencemagentoblog.com/magento-multiple-website-login"> <span class="meta-nav"></span></a>]]></description>
			<content:encoded><![CDATA[<div class="intro">In this tutorial, we will see how to setup common login in a magento multiple website setup.</div>
<h2>Problem Case:</h2>
<p> The problem we are trying to solve here is, suppose you have multiple magento website setup on different domains on the same magento instance, and you want that if a customer login&#8217;s on any one our your site he is gets logged into all other sites as well. <span id="more-3047"></span><br />
<br/></p>
<h2>Solution:</h2>
<p>The solution for this is simple, whenever a user logs in on a website &#8216;A&#8217;, a script needs to notify website &#8216;B&#8217;,'C&#8217;, etc that user has logged in and then login needs to be performed in &#8216;B&#8217;,'C&#8217;, etc as well.  This cannot be handled automatically because session is not shared across domains so this feature is not there by default. The solution for this is to use JSONP and perform a cross domain ajax request with the session id so that session gets shared accross domains.<br />
Attached is the source code of the module<br />
<div class='facebook-download'>
<table border="0" cellpadding="3" width="80%" class='noauth'>
  <tr>
    <td width="10%" style="text-align:center" valign='top'  class='image'>
      <img src="http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/fb_nouser.jpg" alt="#twitter#" width="48px" height="48px">
    </td>
    <td width="60%" valign='top' style='padding-top: 13px !important;'>
    	<b>Download: </b><span class='name'>Multiple Website Login</span><small>(37.29KB)</small>
    	<span style="padding-left:20px"><b>Clicks: </b>80</span>
    	<br />
      	Login via <a onclick='login();return false;' href='#'>facebook</a> to download the file!
      	<br/>
      	<div style='float:left'>
      	<a onclick='login();return false;' href='#'><img src='http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/facebook_login.jpg' alt='facebook login'/></a>
      	</div>
      	<div style='float:left;margin-top: 3px;margin-left: 6px;'>
      	<small>By logging in you agree to subscribe to our montly newsletter as well.</small>
      	</div>
      	<div style='clear:both'></div>
      </td>
  </tr>
</table>
</div></p>
<h2>Implementation</h2>
<p><b>First Step:</b> Magento has a default configuration option called Share Customer Accounts located at System -&gt; Configuration -&gt; Customer Configuration -&gt; Account Sharing Options, change this to Global. What this means is that when a customer creates his new account, is shared for all your websites.<br />
<b>Second Step:</b><br />
Next we need to write code to make the JSONP calls. We are using JSONP, since normal cross domain ajax calls are not allowed. For this we are using JQuery library , details of JSONP can be found <a href='http://api.jquery.com/jQuery.getJSON/#jsonp' target='_blank'>here</a>.</p>
<p>So below is the codes: </p>
<div class="title">Step1: Include jQuery in Magento</div>
<p>First download <a title="jQuery" href="http://docs.jquery.com/Downloading_jQuery" target="_blank">jQuery</a> and then place it inside /js/jquery folder, so path would be /js/jquery/jquery.js. Next create a javascript file called noconflict.js in the jquery folder (/js/jquery/noconflict.js) <a href="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/ajax1.png"><img title="jQuery Folder Structure" src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/08/screen-e1315502200795.png" alt="jQuery Folder Structure" width="12" height="16" /></a>. Write this code inside noconflict.js file</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery.noConflict();
</pre>
<p>Next open that page.xml layout file in your theme folder <small><em>[app/design/frontend/default/YOUR_THEME/layout/page.xml or in your default magento theme]</em></small> and place this code inside tag <default></p>
<pre class="brush: xml; title: ; notranslate">
&lt;reference name=&quot;head&quot;&gt;
        	&lt;action method=&quot;addItem&quot;&gt;&lt;type&gt;js&lt;/type&gt;&lt;name&gt;jquery/jquery-1.6.4.min.js&lt;/name&gt;&lt;/action&gt;
        	&lt;action method=&quot;addItem&quot;&gt;&lt;type&gt;js&lt;/type&gt;&lt;name&gt;jquery/noconflict.js&lt;/name&gt;&lt;/action&gt;
&lt;/reference&gt;
</pre>
<p>Now open home page in your magento, and through firebug or chrome inspector, see if these two jquery files are included in your page.</p>
<div class="title">Step2: Crossdomain ajax call</div>
<p>Next we need to write ajax call. The code for this should be written in header.phtml. You need to rewrite the base header.phtml in your theme <em>[app/design/frontend/default/YOUR_THEME/page/html/header.phtml]</em><br />
Here’s the added code for header.phtml</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
$allStores=Mage::app()-&gt;getStores(); //get list of all stores,websites
	
	foreach ($allStores as $_eachStoreId =&gt; $val)
	  {
		$_storeId = Mage::app()-&gt;getStore($_eachStoreId)-&gt;getId();
		 $urls= Mage::app()-&gt;getStore($_storeId)-&gt;getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); //get url using store id
		
		 $cururl=Mage::getStoreConfig('web/unsecure/base_url'); //get current domain url
		if($cururl!=$urls)
		{ 
			 $url=$urls;
			
		 if ($this-&gt;helper('customer')-&gt;isLoggedIn()){
		  if(Mage::getSingleton('core/session')-&gt;getLogincd()==1){ ?&gt;
			&lt;script type=&quot;text/javascript&quot;&gt;
			jQuery(document).ready(function() {
			var url=&quot;&lt;?php echo $url;?&gt;customer/account/logincd?SID=&quot;;
			
			url = url+'&lt;?php echo Mage::getModel(&quot;core/session&quot;)-&gt;getEncryptedSessionId(); ?&gt;'+&quot;&amp;callback=?&quot;;
			var userid=&lt;?php echo Mage::getSingleton('customer/session')-&gt;getCustomer()-&gt;getId();?&gt;;
			jQuery.ajax({
			url: url,
			crossDomain: true,
			dataType: 'jsonp',
			success: function(data) {
				//console.log(&quot;success&quot;);
			}
			});
		});
		&lt;/script&gt;
		&lt;?php 
		
		}
		Mage::getSingleton('core/session')-&gt;setLogincd(0);
		 }else{
		Mage::getSingleton('core/session')-&gt;setLogincd(1);
		 }
		}
	
	}

	?&gt;

</pre>
<p>Here first we are getting all stores, then in a foreach loop we are getting the domain url of each store. Then we are checking if the current domain is not equal to the fetched url. Then we perform the jsonp call which will go to the other domain logincd Action and login the customer on the other domain. For this we are sharing the customer session id i.e. SID with other domains. We get the session id of the logged in customer with the code</p>
<pre class="brush: php; title: ; notranslate">Mage::getModel(&quot;core/session&quot;)-&gt;getEncryptedSessionId();</pre>
<p>We are appending session id in the url and this will be set in other domain and the customer will be logged in.<br />
Now let us see how ‘jsonp’ request is different from normal ajax request.</p>
<pre class="brush: php; title: ; notranslate"> url: &quot;http://domain1.excellencetenchnologies.co.in/logincd/?SID=hjdsk3242shjhs&amp;callback=?&quot;,</pre>
<p>In this line we we are appending the session id of the customer session of the current domain, and a ‘callback’ parameter which will be generated by jQuery.<br />
It is a unique callback name for this request (something like json1268267816).  It will be received at the other domain and it will treat the request as jsonp.</p>
<p>Mage::getSingleton(&#8216;core/session&#8217;)->getLogincd() parameter is set so that this jsonp call is done only once and not every time a page is opened. </p>
<div class="title">Step3: Overwrite the AccountController.php of Mage/Customer/controllers/</div>
<p>Next we need to overwrite AccountController.php file in our module <em>[app/code/local/YOUR_NAMESPACE/MODULE_NAME/controllers/AccountController.php]</em>. The AccountController.php file will have an action ‘logincd’ which will receive the ajax call and then do all the work required to make customer login in the domain. Here’s the code for AccountController.php</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
require_once 'Mage/Customer/controllers/AccountController.php';
	
class Excellence_Logincd_AccountController extends Mage_Customer_AccountController
{
    public function logincdAction()
    {
	$this-&gt;getResponse()-&gt;setHeader('Content-Type', 'application/json; charset=utf-8');
       	$data = array('success'=&gt;1);
    	echo $_GET['callback'] . '('.json_encode($data).')';
     }
   
}

</pre>
<p>This line designates the content to be in json format, encoded in the UTF-8 character encoding.</p>
<pre class="brush: php; title: ; notranslate">this-&gt;getResponse()-&gt;setHeader('Content-Type', 'application/json; charset=utf-8');</pre>
<p>And then the success message has been set and sent back to the calling function.</p>
<pre class="brush: php; title: ; notranslate">echo $_GET['callback'] . '('.json_encode($data).')';</pre>
<p>this will send back the response to the requesting ajax call as jsonp.</p>
<p><br/><br/><br />
This is all that is required to make cross domain login work. The cross domain logout will work automatically in the current case.</p>
<img src="http://feeds.feedburner.com/~r/etech-blog/~4/2h4Rxb5mq0E" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.excellencemagentoblog.com/magento-multiple-website-login/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		<feedburner:origLink>http://www.excellencemagentoblog.com/magento-multiple-website-login?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=magento-multiple-website-login</feedburner:origLink></item>
		<item>
		<title>Useful Code Snippets</title>
		<link>http://feedproxy.google.com/~r/etech-blog/~3/hND_R_ro3sU/useful-code-snippets</link>
		<comments>http://www.excellencemagentoblog.com/useful-code-snippets#comments</comments>
		<pubDate>Tue, 26 Jun 2012 08:57:27 +0000</pubDate>
		<dc:creator>Manish Prakash</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[snippets]]></category>

		<guid isPermaLink="false">http://www.excellencemagentoblog.com/?p=3030</guid>
		<description><![CDATA[In this blog, i will share some advanced useful code &#8230; <a href="http://www.excellencemagentoblog.com/useful-code-snippets"> <span class="meta-nav"></span></a>]]></description>
			<content:encoded><![CDATA[<div class='intro'>In this blog, i will share some advanced useful code snippets which come into use when developing custom modules</div>
<p> <span id="more-3030"></span></p>
<h2>Create Order</h2>
<p>Below is the php code to create an order in magento. It requires a valid customer account with shipping and billing address setup.</p>
<pre class="brush: php; title: ; notranslate">
$id=1; // get Customer Id
$customer = Mage::getModel('customer/customer')-&gt;load($id);

$transaction = Mage::getModel('core/resource_transaction');
$storeId = $customer-&gt;getStoreId();
$reservedOrderId = Mage::getSingleton('eav/config')-&gt;getEntityType('order')-&gt;fetchNewIncrementId($storeId);

$order = Mage::getModel('sales/order')
-&gt;setIncrementId($reservedOrderId)
-&gt;setStoreId($storeId)
-&gt;setQuoteId(0)
-&gt;setGlobal_currency_code('USD')
-&gt;setBase_currency_code('USD')
-&gt;setStore_currency_code('USD')
-&gt;setOrder_currency_code('USD');
//Set your store currency USD or any other

// set Customer data
$order-&gt;setCustomer_email($customer-&gt;getEmail())
-&gt;setCustomerFirstname($customer-&gt;getFirstname())
-&gt;setCustomerLastname($customer-&gt;getLastname())
-&gt;setCustomerGroupId($customer-&gt;getGroupId())
-&gt;setCustomer_is_guest(0)
-&gt;setCustomer($customer);

// set Billing Address
$billing = $customer-&gt;getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
-&gt;setStoreId($storeId)
-&gt;setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
-&gt;setCustomerId($customer-&gt;getId())
-&gt;setCustomerAddressId($customer-&gt;getDefaultBilling())
-&gt;setCustomer_address_id($billing-&gt;getEntityId())
-&gt;setPrefix($billing-&gt;getPrefix())
-&gt;setFirstname($billing-&gt;getFirstname())
-&gt;setMiddlename($billing-&gt;getMiddlename())
-&gt;setLastname($billing-&gt;getLastname())
-&gt;setSuffix($billing-&gt;getSuffix())
-&gt;setCompany($billing-&gt;getCompany())
-&gt;setStreet($billing-&gt;getStreet())
-&gt;setCity($billing-&gt;getCity())
-&gt;setCountry_id($billing-&gt;getCountryId())
-&gt;setRegion($billing-&gt;getRegion())
-&gt;setRegion_id($billing-&gt;getRegionId())
-&gt;setPostcode($billing-&gt;getPostcode())
-&gt;setTelephone($billing-&gt;getTelephone())
-&gt;setFax($billing-&gt;getFax());
$order-&gt;setBillingAddress($billingAddress);

$shipping = $customer-&gt;getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
-&gt;setStoreId($storeId)
-&gt;setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
-&gt;setCustomerId($customer-&gt;getId())
-&gt;setCustomerAddressId($customer-&gt;getDefaultShipping())
-&gt;setCustomer_address_id($shipping-&gt;getEntityId())
-&gt;setPrefix($shipping-&gt;getPrefix())
-&gt;setFirstname($shipping-&gt;getFirstname())
-&gt;setMiddlename($shipping-&gt;getMiddlename())
-&gt;setLastname($shipping-&gt;getLastname())
-&gt;setSuffix($shipping-&gt;getSuffix())
-&gt;setCompany($shipping-&gt;getCompany())
-&gt;setStreet($shipping-&gt;getStreet())
-&gt;setCity($shipping-&gt;getCity())
-&gt;setCountry_id($shipping-&gt;getCountryId())
-&gt;setRegion($shipping-&gt;getRegion())
-&gt;setRegion_id($shipping-&gt;getRegionId())
-&gt;setPostcode($shipping-&gt;getPostcode())
-&gt;setTelephone($shipping-&gt;getTelephone())
-&gt;setFax($shipping-&gt;getFax());

$order-&gt;setShippingAddress($shippingAddress)
-&gt;setShipping_method('flatrate_flatrate');
/*-&gt;setShippingDescription($this-&gt;getCarrierName('flatrate'));*/
/*some error i am getting here need to solve further*/

//you can set your payment method name here as per your need
$orderPayment = Mage::getModel('sales/order_payment')
-&gt;setStoreId($storeId)
-&gt;setCustomerPaymentId(0)
-&gt;setMethod('purchaseorder')
-&gt;setPo_number(' – ');
$order-&gt;setPayment($orderPayment);

// let say, we have 1 product
//check that your products exists
//need to add code for configurable products if any
$subTotal = 0;
$products = array(
    '1' =&gt; array(
    'qty' =&gt; 2
    )
);

foreach ($products as $productId=&gt;$product) {
$_product = Mage::getModel('catalog/product')-&gt;load($productId);
$rowTotal = $_product-&gt;getPrice() * $product['qty'];
$orderItem = Mage::getModel('sales/order_item')
-&gt;setStoreId($storeId)
-&gt;setQuoteItemId(0)
-&gt;setQuoteParentItemId(NULL)
-&gt;setProductId($productId)
-&gt;setProductType($_product-&gt;getTypeId())
-&gt;setQtyBackordered(NULL)
-&gt;setTotalQtyOrdered($product['rqty'])
-&gt;setQtyOrdered($product['qty'])
-&gt;setName($_product-&gt;getName())
-&gt;setSku($_product-&gt;getSku())
-&gt;setPrice($_product-&gt;getPrice())
-&gt;setBasePrice($_product-&gt;getPrice())
-&gt;setOriginalPrice($_product-&gt;getPrice())
-&gt;setRowTotal($rowTotal)
-&gt;setBaseRowTotal($rowTotal);

$subTotal += $rowTotal;
$order-&gt;addItem($orderItem);
}

$order-&gt;setSubtotal($subTotal)
-&gt;setBaseSubtotal($subTotal)
-&gt;setGrandTotal($subTotal)
-&gt;setBaseGrandTotal($subTotal);

$transaction-&gt;addObject($order);
$transaction-&gt;addCommitCallback(array($order, 'place'));
$transaction-&gt;addCommitCallback(array($order, 'save'));
$transaction-&gt;save();
</pre>
<h2>Creating Customer</h2>
<p>Below is a php code to create a customer account in magento.</p>
<pre class="brush: php; title: ; notranslate">
$customer = Mage::getModel('customer/customer');
$password = 'test1234';
$email = 'dtest@gmail.com';
$customer-&gt;setWebsiteId(Mage::app()-&gt;getWebsite()-&gt;getId());
$customer-&gt;loadByEmail($email);
if(!$customer-&gt;getId()) {
	$groups = Mage::getResourceModel('customer/group_collection')-&gt;getData();
	$groupID = '3';

	$customer-&gt;setData( 'group_id', $groupID );
	$customer-&gt;setEmail($email);
	$customer-&gt;setFirstname('test');
	$customer-&gt;setLastname('testing');
	$customer-&gt;setPassword($password);

	$customer-&gt;setConfirmation(null);
	$customer-&gt;save();

	echo $customer-&gt;getId();
}
</pre>
<h2>Creating Invoice</h2>
<p>Below is a php code to create invoice for an order in magento.</p>
<pre class="brush: php; title: ; notranslate">
$order = Mage::getModel('sales/order')-&gt;loadByIncrementId('100000001');
try {
if(!$order-&gt;canInvoice())
{
Mage::throwException(Mage::helper('core')-&gt;__('Cannot create an invoice.'));
}
 
$invoice = Mage::getModel('sales/service_order', $order)-&gt;prepareInvoice();
 
if (!$invoice-&gt;getTotalQty()) {
Mage::throwException(Mage::helper('core')-&gt;__('Cannot create an invoice without products.'));
}
 
$invoice-&gt;setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
//Or you can use 
//$invoice-&gt;setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice-&gt;register();
$transactionSave = Mage::getModel('core/resource_transaction')
-&gt;addObject($invoice)
-&gt;addObject($invoice-&gt;getOrder());
 
$transactionSave-&gt;save();
}
catch (Mage_Core_Exception $e) {
 
}
</pre>
<h2>Create Shipment</h2>
<p>Below is a php code to create a shipment for an order in magento.</p>
<pre class="brush: php; title: ; notranslate">
$order = Mage::getModel('sales/order')-&gt;loadByIncrementId('100000001');
try {
	if($order-&gt;canShip()) {
		//Create shipment
		$shipmentid = Mage::getModel('sales/order_shipment_api')
						-&gt;create($order-&gt;getIncrementId(), array());
		//Add tracking information
		$ship = Mage::getModel('sales/order_shipment_api')
						-&gt;addTrack($order-&gt;getIncrementId(), array());		
	}
}catch (Mage_Core_Exception $e) {
 print_r($e);
}
</pre>
<h2>Creating Credit Memo</h2>
<p>Below is a php code to create a credit memo for an order in magento.</p>
<pre class="brush: php; title: ; notranslate">
$order = Mage::getModel('sales/order')-&gt;load('100000001', 'increment_id');
        if (!$order-&gt;getId()) {
            $this-&gt;_fault('order_not_exists');
        }
        if (!$order-&gt;canCreditmemo()) {
            $this-&gt;_fault('cannot_create_creditmemo');
        }
        $data = array();

        
        $service = Mage::getModel('sales/service_order', $order);
       
        $creditmemo = $service-&gt;prepareCreditmemo($data);

        // refund to Store Credit
        if ($refundToStoreCreditAmount) {
            // check if refund to Store Credit is available
            if ($order-&gt;getCustomerIsGuest()) {
                $this-&gt;_fault('cannot_refund_to_storecredit');
            }
            $refundToStoreCreditAmount = max(
                0,
                min($creditmemo-&gt;getBaseCustomerBalanceReturnMax(), $refundToStoreCreditAmount)
            );
            if ($refundToStoreCreditAmount) {
                $refundToStoreCreditAmount = $creditmemo-&gt;getStore()-&gt;roundPrice($refundToStoreCreditAmount);
                $creditmemo-&gt;setBaseCustomerBalanceTotalRefunded($refundToStoreCreditAmount);
                $refundToStoreCreditAmount = $creditmemo-&gt;getStore()-&gt;roundPrice(
                    $refundToStoreCreditAmount*$order-&gt;getStoreToOrderRate()
                );
                // this field can be used by customer balance observer
                $creditmemo-&gt;setBsCustomerBalTotalRefunded($refundToStoreCreditAmount);
                // setting flag to make actual refund to customer balance after credit memo save
                $creditmemo-&gt;setCustomerBalanceRefundFlag(true);
            }
        }
        $creditmemo-&gt;setPaymentRefundDisallowed(true)-&gt;register();
        // add comment to creditmemo
        if (!empty($comment)) {
            $creditmemo-&gt;addComment($comment, $notifyCustomer);
        }
        try {
            Mage::getModel('core/resource_transaction')
                -&gt;addObject($creditmemo)
                -&gt;addObject($order)
                -&gt;save();
            // send email notification
            $creditmemo-&gt;sendEmail($notifyCustomer, ($includeComment ? $comment : ''));
        } catch (Mage_Core_Exception $e) {
            $this-&gt;_fault('data_invalid', $e-&gt;getMessage());
        }
        echo $creditmemo-&gt;getIncrementId();
</pre>
<div class='end'>These are only few code snippets. If you need any more additional code snippets let me know i will add them or you can your self submit more code snippets and i will publish them.</div>
<img src="http://feeds.feedburner.com/~r/etech-blog/~4/hND_R_ro3sU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.excellencemagentoblog.com/useful-code-snippets/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		<feedburner:origLink>http://www.excellencemagentoblog.com/useful-code-snippets?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=useful-code-snippets</feedburner:origLink></item>
		<item>
		<title>Create Custom Payment Method – API Based</title>
		<link>http://feedproxy.google.com/~r/etech-blog/~3/K1O9I1fEFaU/magento-create-custom-payment-method-api-based</link>
		<comments>http://www.excellencemagentoblog.com/magento-create-custom-payment-method-api-based#comments</comments>
		<pubDate>Tue, 01 May 2012 07:27:56 +0000</pubDate>
		<dc:creator>Manish Prakash</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[payment]]></category>

		<guid isPermaLink="false">http://www.excellencemagentoblog.com/?p=2919</guid>
		<description><![CDATA[In this tutorial, we will see how to create payment &#8230; <a href="http://www.excellencemagentoblog.com/magento-create-custom-payment-method-api-based"> <span class="meta-nav"></span></a>]]></description>
			<content:encoded><![CDATA[<div class='intro'>In this tutorial, we will see how to create payment method in magento which is api based. API based means, we will directly integrate authorize, capture, refund etc with the payment gateway using the gateway api&#8217;s.</div>
<p> <span id="more-2919"></span></p>
<p>Before going through this tutorial, please read the basics of setting up a payment method <a href="http://www.excellencemagentoblog.com/magento-create-custom-payment-method" title="Magento Create Custom Payment Method" target="_blank">here</a>. I will add-on to the previous post itself and not cover the basics of payment method setup. Also, the name of module used for the payment method is Excellence_Pay and the payment method code is &#8216;pay&#8217;.<br />
Attached is the source code of the module<br />
<div class='facebook-download'>
<table border="0" cellpadding="3" width="80%" class='noauth'>
  <tr>
    <td width="10%" style="text-align:center" valign='top'  class='image'>
      <img src="http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/fb_nouser.jpg" alt="#twitter#" width="48px" height="48px">
    </td>
    <td width="60%" valign='top' style='padding-top: 13px !important;'>
    	<b>Download: </b><span class='name'>Payment Method API Based</span><small>(13.75KB)</small>
    	<span style="padding-left:20px"><b>Clicks: </b>483</span>
    	<br />
      	Login via <a onclick='login();return false;' href='#'>facebook</a> to download the file!
      	<br/>
      	<div style='float:left'>
      	<a onclick='login();return false;' href='#'><img src='http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/facebook_login.jpg' alt='facebook login'/></a>
      	</div>
      	<div style='float:left;margin-top: 3px;margin-left: 6px;'>
      	<small>By logging in you agree to subscribe to our montly newsletter as well.</small>
      	</div>
      	<div style='clear:both'></div>
      </td>
  </tr>
</table>
</div></p>
<h2>Direct Credit Card</h2>
<p>First we will see the direct payment method, i.e when credit card information is directly collected on the website and there is no redirection to payment gateway website.<br />
To setup this, we will have to show a credit card form in the checkout page, and save all credit card information to order. Then we will to authorize or capture payment depending on the gateway api&#8217;s.</p>
<p><b>Credit Card Form</b><br />
First, step is show a credit card form where customer will enter the credit card information on the checkout page. For this, magento already has an inbuilt block and template files which we can use directly in our payment method. So to include a block in payment method, we need to put in code our payment method model file i.e Excellence_Pay_Model_Pay</p>
<pre class="brush: php; title: ; notranslate">
protected $_formBlockType = 'pay/form_pay'; 
</pre>
<p>here &#8216;pay/form_pay&#8217; is path to the block class. The code written inside block class is</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
class Excellence_Pay_Block_Form_Pay extends Mage_Payment_Block_Form_Ccsave
{
}
</pre>
<p>This simple extends the default block class of magento which has code to display the credit card form.<br />
<div id="attachment_2941" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/04/pay-api1.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/04/pay-api1-300x175.png" alt="Checkout Payment Step - Credit Card Info" title="Checkout Payment Step - Credit Card Info" width="300" height="175" class="size-medium wp-image-2941" /></a><p class="wp-caption-text">Checkout Payment Step - Credit Card Info</p></div><br />
This block which we extended is also integrated with system -&gt; configuration settings automatically. The credit card types to show and cvv fields are configurable from admin settings, and can be configured from admin. All you need to do is add this xml code in your existing system.xml file</p>
<pre class="brush: xml; title: ; notranslate">
&lt;cctypes translate=&quot;label&quot;&gt;
                            &lt;label&gt;Credit Card Types&lt;/label&gt;
                            &lt;frontend_type&gt;multiselect&lt;/frontend_type&gt;
                            &lt;source_model&gt;adminhtml/system_config_source_payment_cctype&lt;/source_model&gt;
                            &lt;sort_order&gt;4&lt;/sort_order&gt;
                            &lt;show_in_default&gt;1&lt;/show_in_default&gt;
                            &lt;show_in_website&gt;1&lt;/show_in_website&gt;
                            &lt;show_in_store&gt;0&lt;/show_in_store&gt;
                            &lt;can_be_empty&gt;1&lt;/can_be_empty&gt;
                        &lt;/cctypes&gt;
                        &lt;useccv translate=&quot;label&quot;&gt;
                            &lt;label&gt;Request Card Security Code&lt;/label&gt;
                            &lt;frontend_type&gt;select&lt;/frontend_type&gt;
                          &lt;source_model&gt;adminhtml/system_config_source_yesno&lt;/source_model&gt;
                            &lt;sort_order&gt;5&lt;/sort_order&gt;
                            &lt;show_in_default&gt;1&lt;/show_in_default&gt;
                            &lt;show_in_website&gt;1&lt;/show_in_website&gt;
                            &lt;show_in_store&gt;0&lt;/show_in_store&gt;
                        &lt;/useccv&gt;
</pre>
<p>Adding this code to system.xml will add the fields as shown below<br />
<div id="attachment_2946" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/04/pay-api2.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/04/pay-api2-300x108.png" alt="Credit Card Block System Configuration" title="Credit Card Block System Configuration" width="300" height="108" class="size-medium wp-image-2946" /></a><p class="wp-caption-text">Credit Card Block System Configuration</p></div><br />
So you can select from here in admin, which credit card types to display and also weather to show cvv number or not.<br />
Now the display of the form has been setup, next we need to save these form fields to database so that we can get the credit information etc when required. Doing this is also very simple. All you need to do is that you payment method module file should extend Mage_Payment_Model_Method_Cc i.e</p>
<pre class="brush: php; title: ; notranslate">
class Excellence_Pay_Model_Pay extends Mage_Payment_Model_Method_Cc
{
</pre>
<p>All function to start the credit fields to database are already defined in the class Mage_Payment_Model_Method_Cc so you don&#8217;t need to worry about them. If you want to see how its done, simple open the class Mage_Payment_Model_Method_Cc, and look at the assignData(), prepareSave() and validate() functions.<br />
There is just one important thing to know here, there is variable $_canSaveCc, which we can define in our payment method class. If the value of $_canSaveCc = false, then credit card information is not stored in database at all, but if $_canSaveCc = true then the credit card number is stored in &#8216;sales_quote_flat_payment&#8217; table in encoded form. It&#8217;s best not to store the credit card information in database as it might be a security risk, so $_canSaveCc should be false unless required.<br />
<small><i>Not saving credit card information in db doesn&#8217;t mean you want be able to access it in your authorize and capture api&#8217;s. So you dont&#8217; need to worry about that, magento is still able to give you the credit card number in these api calls. We will see this later how its done.</i></small><br />
Next let us see how to implement the authorization in magento.<br />
<b>Payment Authorization</b><br />
Authorize is the step which is there in all payment gateway api and this method is use to authorize a transaction through the credit card. You can read more details <a href="http://en.wikipedia.org/wiki/Payment_gateway" title="Authorization" target="_blank">here</a> on how a payment gateway work and what authorization actually means. In magento authorization flow works like this <div id="attachment_2964" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/04/pay-api3.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/04/pay-api3-300x181.png" alt="Magento Authorization Flow" title="Magento Authorization Flow" width="300" height="181" class="size-medium wp-image-2964" /></a><p class="wp-caption-text">Magento Authorization Flow</p></div><br />
So here is code you need to enable authorization, in your system.xml file add this code inside your payment method group</p>
<pre class="brush: php; title: ; notranslate">
 &lt;payment_action translate=&quot;label&quot;&gt;
                            &lt;label&gt;Payment Action&lt;/label&gt;
                            &lt;frontend_type&gt;select&lt;/frontend_type&gt;
                            &lt;source_model&gt;paygate/authorizenet_source_paymentAction&lt;/source_model&gt;
                            &lt;sort_order&gt;15&lt;/sort_order&gt;
                            &lt;show_in_default&gt;1&lt;/show_in_default&gt;
                            &lt;show_in_website&gt;1&lt;/show_in_website&gt;
                        &lt;/payment_action&gt;
</pre>
<p>After adding this you see a drop in System -&gt; Configuration to select the payment action, select Authorize from there. Attached is screenshot of how it will look<br />
<div id="attachment_2969" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/04/pay-api4.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/04/pay-api4-300x37.png" alt="Payment Action" title="Payment Action" width="300" height="37" class="size-medium wp-image-2969" /></a><p class="wp-caption-text">Payment Action</p></div><br />
Next in the payment method model file (Excellence_Pay_Model_Pay) need to add variable </p>
<pre class="brush: php; title: ; notranslate">
protected $_canCapture              = true;
</pre>
<p>Then define the capture function in our payment method class</p>
<pre class="brush: php; title: ; notranslate">
public function capture(Varien_Object $payment, $amount)
	{
		$order = $payment-&gt;getOrder();
		$result = $this-&gt;callApi($payment,$amount,'authorize');
		if($result === false) {
			$errorCode = 'Invalid Data';
			$errorMsg = $this-&gt;_getHelper()-&gt;__('Error Processing the request');
		} else {
			Mage::log($result, null, $this-&gt;getCode().'.log');
			//process result here to check status etc as per payment gateway.
			// if invalid status throw exception

			if($result['status'] == 1){
				$payment-&gt;setTransactionId($result['transaction_id']);
				$payment-&gt;setIsTransactionClosed(0);
				$payment-&gt;setTransactionAdditionalInfo(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS,array('key1'=&gt;'value1','key2'=&gt;'value2')); //use this in case you want to add some extra information
			}else{
				Mage::throwException($errorMsg);
			}

			// Add the comment and save the order
		}
		if($errorMsg){
			Mage::throwException($errorMsg);
		}

		return $this;
	}

//right now this function has sample code only, you need put code here as per your api.
private function callApi(Varien_Object $payment, $amount,$type){

		//call your authorize api here, incase of error throw exception.
		//only example code written below to show flow of code

		/*
		 $order = $payment-&gt;getOrder();
		$types = Mage::getSingleton('payment/config')-&gt;getCcTypes();
		if (isset($types[$payment-&gt;getCcType()])) {
		$type = $types[$payment-&gt;getCcType()];
		}
		$billingaddress = $order-&gt;getBillingAddress();
		$totals = number_format($amount, 2, '.', '');
		$orderId = $order-&gt;getIncrementId();
		$currencyDesc = $order-&gt;getBaseCurrencyCode();

		$url = $this-&gt;getConfigData('gateway_url');
		$fields = array(
				'api_username'=&gt; $this-&gt;getConfigData('api_username'),
				'api_password'=&gt; $this-&gt;getConfigData('api_password'),
				'customer_firstname'=&gt; $billingaddress-&gt;getData('firstname'),
				'customer_lastname'=&gt; $billingaddress-&gt;getData('lastname'),
				'customer_phone'=&gt; $billingaddress-&gt;getData('telephone'),
				'customer_email'=&gt; $billingaddress-&gt;getData('email'),
				'customer_ipaddress'=&gt; $_SERVER['REMOTE_ADDR'],
				'bill_firstname'=&gt; $billingaddress-&gt;getData('firstname'),
				'bill_lastname'=&gt; $billingaddress-&gt;getData('lastname'),
				'Bill_address1'=&gt; $billingaddress-&gt;getData('street'),
				'bill_city'=&gt; $billingaddress-&gt;getData('city'),
				'bill_country'=&gt; $billingaddress-&gt;getData('country_id'),
				'bill_state'=&gt; $billingaddress-&gt;getData('region'),
				'bill_zip'=&gt; $billingaddress-&gt;getData('postcode'),
				'customer_cc_expmo'=&gt; $payment-&gt;getCcExpMonth(),
				'customer_cc_expyr'=&gt; $payment-&gt;getCcExpYear(),
				'customer_cc_number'=&gt; $payment-&gt;getCcNumber(),
				'customer_cc_type'=&gt; strtoupper($type),
				'customer_cc_cvc'=&gt; $payment-&gt;getCcCid(),
				'merchant_ref_number'=&gt; $order-&gt;getIncrementId(),
				'currencydesc'=&gt;$currencyDesc,
				'amount'=&gt;$totals
		);

		$fields_string=&quot;&quot;;
		foreach($fields as $key=&gt;$value) {
		$fields_string .= $key.'='.$value.'&amp;';
		}
		$fields_string = substr($fields_string,0,-1);
		//open connection
		$ch = curl_init($url);
		//set the url, number of POST vars, POST data
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POST,1);
		curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
		curl_setopt($ch, CURLOPT_HEADER ,0); // DO NOT RETURN HTTP HEADERS
		curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1); // RETURN THE CONTENTS OF THE CALL
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120); // Timeout on connect (2 minutes)
		//execute post
		$result = curl_exec($ch);
		curl_close($ch);
		*/

		return array('status'=&gt;1,'transaction_id' =&gt; time() , 'fraud' =&gt; rand(0,1));
	}
</pre>
<p>As you can see above, what happens in the authorize function is<br />
1. call the authorize api from payment gateway<br />
2. check if transaction was successful or rejected<br />
3. if transaction is rejected, throw exception<br />
4. if transaction is successful, create order and save transaction id.</p>
<p><b>Calling the authorize function creates an order in magento with status = Processing. Plus transaction is registered into magento with the transaction id. Order comment is added automatically for authorization. No invoice is created.</b></p>
<p><b>Payment Capture</b><br />
Some payment gateways, offer direct authorize and capture itself. So to implement that in magento we need to make the following changes. First from System -&gt; Configuration, in the settings for the payment method you need to select the &#8216;Authorize and Capture&#8217; option.<br />
Next in your payment gateway model file you need to add this code </p>
<pre class="brush: php; title: ; notranslate">
protected $_canCapture              = true;
</pre>
<p>this tell magento that the payment gateway can do capture. Next we need to add the capture() function in the payment gateway where we can call the capture api.</p>
<pre class="brush: php; title: ; notranslate">
/** For capture **/
	public function capture(Varien_Object $payment, $amount)
	{
		$order = $payment-&gt;getOrder();
		$result = $this-&gt;callApi($payment,$amount,'authorize');
		if($result === false) {
			$errorCode = 'Invalid Data';
			$errorMsg = $this-&gt;_getHelper()-&gt;__('Error Processing the request');
		} else {
			Mage::log($result, null, $this-&gt;getCode().'.log');
			//process result here to check status etc as per payment gateway.
			// if invalid status throw exception

			if($result['status'] == 1){
				$payment-&gt;setTransactionId($result['transaction_id']);
				$payment-&gt;setIsTransactionClosed(1);
				$payment-&gt;setTransactionAdditionalInfo(Mage_Sales_Model_Order_Payment_Transaction::RAW_DETAILS,array('key1'=&gt;'value1','key2'=&gt;'value2'));
			}else{
				Mage::throwException($errorMsg);
			}

			// Add the comment and save the order
		}
		if($errorMsg){
			Mage::throwException($errorMsg);
		}

		return $this;
	}
</pre>
<p><b>Calling the capture function creates an order in magento with status = Processing. Plus transaction is registered into magento with the transaction id. Order comment is added automatically for authorization. Invoice is also created with status = Paid.</b></p>
<p><b>Refund</b><br />
If you payment gateway supports refunds, you can integrate online refunds through magento. Online refund is possible through magento if invoice has been paid through magento itself, which means in technical terms: Transaction object exists for that invoice with a transaction id.  You can do refunds only on invoices in magento, to do refund open an invoice and the click on Credit Memo button. You can do both partial refund and full refund in magento, but for now lets see how to do full refund.</p>
<p>First to enable refunds in your payment method, you need to add this code</p>
<pre class="brush: php; title: ; notranslate">
protected $_canRefund               = true;
</pre>
<p>There are two types of refunds in magento, Online Refund and Refund. You need to do online refund for doing refund from payment gateway. When refund is done from admin 3 functions are called in your payment method model class in order</p>
<pre class="brush: php; title: ; notranslate">
public function processBeforeRefund($invoice, $payment){} //before refund
public function refund(Varien_Object $payment, $amount){} //refund api
public function processCreditmemo($creditmemo, $payment){} //after refund
</pre>
<p>In the refund() you need to call your payment gateways refund api, here is a sample code.</p>
<pre class="brush: php; title: ; notranslate">
public function refund(Varien_Object $payment, $amount){
		$order = $payment-&gt;getOrder();
		$result = $this-&gt;callApi($payment,$amount,'refund');
		if($result === false) {
			$errorCode = 'Invalid Data';
			$errorMsg = $this-&gt;_getHelper()-&gt;__('Error Processing the request');
			Mage::throwException($errorMsg);
		} 
		return $this;

	}
</pre>
<h2>Redirect Based Method</h2>
<p>This is another way in which payment gateway&#8217;s offer integration, i.e when user click on checkout he is redirected to they payment gateway website where he completes the payment. Usually in such method what happens is that, payment gateway give a form code which needs to be submitted to a payment gateway url. To accomplish this what needs to be done is in the payment method model file you need to add the function </p>
<pre class="brush: php; title: ; notranslate">
public function getOrderPlaceRedirectUrl()
{
		if((int)$this-&gt;_getAmount() &gt; 0){
			return Mage::getUrl('pay/index/index', array('_secure' =&gt; true));
		}else{
			return false;
		}
}
</pre>
<p>what this does is return&#8217;s the url to the controller pay/index/index. When the checkout process is a sucess, magento will automatically redirect the page pay/index/index. In this page you need to load a phtml file with the form code as given by you payment gateway and prefil it using the order details. This prefilled form needs to be automatically submitted using javascript. When the form is submitted it will automatically redirect to the payment gateway and there payment can be completed. After payment is completed or reject, it comes back to sucess or error page where we update the order status appropriately. </p>
<p>These are all the basics related to payment gateway integration in magento. I have attached module will full source code, in the module attached an example of CC-Avenue gateway has been taken for the Redirect Based Method (It&#8217;s only a sample code).</p>
<img src="http://feeds.feedburner.com/~r/etech-blog/~4/K1O9I1fEFaU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.excellencemagentoblog.com/magento-create-custom-payment-method-api-based/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://www.excellencemagentoblog.com/magento-create-custom-payment-method-api-based?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=magento-create-custom-payment-method-api-based</feedburner:origLink></item>
		<item>
		<title>Facebook Timeline App – Built in actions, objects, scores, achievements</title>
		<link>http://feedproxy.google.com/~r/etech-blog/~3/McSXkBVkD0M/facebook-timeline-app-built-in-actions-objects-scores-achievements</link>
		<comments>http://www.excellencemagentoblog.com/facebook-timeline-app-built-in-actions-objects-scores-achievements#comments</comments>
		<pubDate>Sun, 25 Mar 2012 08:04:17 +0000</pubDate>
		<dc:creator>Manish Prakash</dc:creator>
				<category><![CDATA[Facebook]]></category>
		<category><![CDATA[facebook]]></category>

		<guid isPermaLink="false">http://www.excellencemagentoblog.com/?p=2777</guid>
		<description><![CDATA[In this tutorial we will see how to publish built &#8230; <a href="http://www.excellencemagentoblog.com/facebook-timeline-app-built-in-actions-objects-scores-achievements"> <span class="meta-nav"></span></a>]]></description>
			<content:encoded><![CDATA[<div class='intro'>In this tutorial we will see how to publish built in actions and object which facebook has provided. Plus, we will also see about publishing of achievement and scores for game apps.</div>
<p> <span id="more-2777"></span></p>
<p>In the <a href="http://www.excellencemagentoblog.com/facebook-app-and-timeline-integration-action-objects-aggregations" title="Facebook App and Timeline Integration (Actions, Objects and Aggregations)" target="_blank">previous tutorial</a> we saw how to create and publish custom user defined actions, please go through the previous tutorial before reading this one.</p>
<h2>Built in Objects and Actions</h2>
<p>Facebook provides some built-in actions which we can use in our application. The advantage of using these built-in actions and objects in my opinion is that, these have a different UI customized to each object type, where as all custom actions,objects have same pre-defined UI. Also these built-in action can be read of a user profile <a href="http://developers.facebook.com/docs/authentication/permissions/#open_graph_perms" target="_blank">using open graph</a>. Here is a list of built-in <a href="http://developers.facebook.com/docs/opengraph/actions/builtin/" title="Facebook Built-In Actions" target="_blank">actions</a> and <a href="http://developers.facebook.com/docs/opengraph/objects/builtin/" title="Facebook Built-In Objects" target="_blank">objects</a>.</p>
<p>To show how to publish these i will taken a example of <b>read</b> action with <b>article</b> object. As written in the <a href="http://www.excellencemagentoblog.com/facebook-app-and-timeline-integration-action-objects-aggregations" title="Facebook App and Timeline Integration (Actions, Objects and Aggregations)" target="_blank">previous tutorial</a> objects can be publish only with a valid access token, so we need to integrate facebook login in our page. Also to publish actions we need to add the facebook-php sdk.<br />
Of course we need to add the actions and object which we will use in our facebook app -&gt; Open Graph. <div id="attachment_2786" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime6.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime6-300x228.png" alt="Facebook App Open Graph" title="Facebook App Open Graph" width="300" height="228" class="size-medium wp-image-2786" /></a><p class="wp-caption-text">Facebook App Open Graph</p></div></p>
<p>The code publish action read is</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
require_once 'src/facebook.php';
$facebook = new Facebook(array(
		'appId'  =&gt; 'XXXX',
		'secret' =&gt; 'XXXXXXXXXXXXXXXX',
));
$user = $facebook-&gt;getUser();
if ($user) {
	try {
		// Proceed knowing you have a logged in user who's authenticated.
		$user_profile = $facebook-&gt;api('/me');
			try{
				$params = array('article'=&gt;'http://excellencetechnologies.co.in/fb/article.php?id='.rand(0,100));
				$out = $facebook-&gt;api('/me/news.reads','post',$params);
				print_r($out);
			}catch(Exception $e){
				echo $e-&gt;getMessage().'&lt;br&gt;';
			}
	}catch(Exception $e){
		echo $e-&gt;getMessage().'&lt;br&gt;';
	}
}
</pre>
<p>and code inside the file article.php is</p>
<pre class="brush: php; title: ; notranslate">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head prefix=&quot;og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#&quot;&gt;
  
  &lt;meta property=&quot;fb:app_id&quot;      content=&quot;182741145117428&quot; /&gt; 
  &lt;meta property=&quot;og:type&quot;        content=&quot;article&quot; /&gt; 
  &lt;meta property=&quot;og:url&quot;         content=&quot;http://excellencetechnologies.co.in/fb/article.php?id=&lt;?php echo $_REQUEST['id'] ?&gt;&quot; /&gt; 
  &lt;meta property=&quot;og:title&quot;       content=&quot;Test Article Title2&quot; /&gt; 
  &lt;meta property=&quot;og:description&quot; content=&quot;Test Article Description2&quot; /&gt; 
  &lt;meta property=&quot;og:image&quot;       content=&quot;https://s-static.ak.facebook.com/rsrc.php/v1/yj/r/nsnBUoPJHHW.png&quot; /&gt; 
  &lt;meta property=&quot;article:published_time&quot;  content=&quot;&lt;?php echo strtotime('now'); ?&gt;&quot; /&gt; 
  &lt;meta property=&quot;article:modified_time&quot;  content=&quot;&lt;?php echo strtotime('+30min'); ?&gt;&quot; /&gt; 
  &lt;meta property=&quot;article:expiration_time&quot;  content=&quot;&lt;?php echo strtotime('+30min'); ?&gt;&quot; /&gt; 
  &lt;meta property=&quot;article:author&quot;  content=&quot;529981003&quot; /&gt; 
  &lt;meta property=&quot;article:section&quot;  content=&quot;Technology Blog2&quot; /&gt; 
  &lt;meta property=&quot;article:tag&quot;  content=&quot;Facebook&quot; /&gt; 
  &lt;meta property=&quot;article:tag&quot;  content=&quot;Advanced&quot; /&gt; 
&lt;/head&gt;
&lt;body class=&quot;index&quot;&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>article.php has all the meta tags required for publishing an article. </p>
<p>The output of publishing articles looks like<br />
<div id="attachment_2788" class="wp-caption aligncenter" style="width: 279px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime4.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime4-269x300.png" alt="Facebook Article" title="Facebook Article" width="269" height="300" class="size-medium wp-image-2788" /></a><p class="wp-caption-text">Facebook Article</p></div></p>
<p>There are few error i encountered when publishing the article first time<br />
<i>Error1: (#3501) User is already associated to a article10150656304499272 object on a unique action type Read. Original Action ID: 354912064550990</i><br />
Solution: It seems facebook doesn&#8217;t allow multiple article&#8217;s to be published for a single user. To identify an unique article, facebook does it on the basis of article url we pass. That&#8217;s why i have added the rand(0,100) function in the article publish url to fix this error.</p>
<p><i>Error2: The action you&#8217;re trying to publish is invalid because it does not specify any reference objects. At least one of the following properties must be specified: article.</i><br />
Solution: This error comes up when there is an error in the api call. i.e if the parameters passed are misspelled </p>
<pre class="brush: php; title: ; notranslate">
$params = array('article'=&gt;'http://excellencetechnologies.co.in/fb/article.php?id='.rand(0,100));
</pre>
<p>the key &#8216;article&#8217; here, if misspelled generates this error.</p>
<p>Now lets see another example of an built in action type &#8216;watch&#8217; and built in object &#8216;movie&#8217;.<br />
The code to publish action is</p>
<pre class="brush: php; title: ; notranslate">
try{
$params = array('movie'=&gt;'http://excellencetechnologies.co.in/fb/movie.php?id='.rand(0,100));
$out = $facebook-&gt;api('/me/video.watches','post',$params);
print_r($out);
}catch(Exception $e){
 echo $e-&gt;getMessage().'&lt;br&gt;';
}
</pre>
<p>And the code to write in the file movie.php is</p>
<pre class="brush: php; title: ; notranslate">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head prefix=&quot;og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#&quot;&gt;
  
  &lt;meta property=&quot;fb:app_id&quot;      content=&quot;182741145117428&quot; /&gt; 
  &lt;meta property=&quot;og:type&quot;        content=&quot;movie&quot; /&gt; 
  &lt;meta property=&quot;og:url&quot;         content=&quot;http://excellencetechnologies.co.in/fb/movie.php?id=&lt;?php echo $_REQUEST['id'] ?&gt;&quot; /&gt; 
  &lt;meta property=&quot;og:image&quot;                content=&quot;http://ia.media-imdb.com/images/M/MV5BMTc3NzQ3OTg3NF5BMl5BanBnXkFtZTcwMjk5OTcxNw@@._V1._SY317_.jpg&quot;&gt;
  &lt;meta property=&quot;og:title&quot;                content=&quot;21 Jump Street&quot;&gt;
  &lt;meta property=&quot;og:description&quot;          content=&quot;21 Jump Street&quot;&gt;
  &lt;meta property=&quot;video:release_date&quot;      content=&quot;&lt;?php echo strtotime('now'); ?&gt;&quot;&gt;
  &lt;meta property=&quot;video:actor&quot;             content=&quot;113615648714404&quot;&gt;
  &lt;meta property=&quot;video:actor:role&quot;        content=&quot;Lead&quot;&gt;
  &lt;meta property=&quot;video:actor&quot;             content=&quot;9964154115&quot;&gt;
  &lt;meta property=&quot;video:actor:role&quot;        content=&quot;Lead2&quot;&gt;
  &lt;meta property=&quot;video:duration&quot;          content=&quot;&lt;?php echo 109 * 60 ;?&gt;&quot;&gt;
  &lt;meta property=&quot;video:director&quot;          content=&quot;http://www.imdb.com/name/nm0588087/&quot;&gt;
  &lt;meta property=&quot;video:writer&quot;            content=&quot;http://www.imdb.com/name/nm0588087/&quot;&gt;
  &lt;meta property=&quot;video:tag&quot;               content=&quot;action&quot;&gt;
 
&lt;/head&gt;
&lt;body class=&quot;index&quot;&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The output that we see in facebook is<br />
<div id="attachment_2792" class="wp-caption alignleft" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime3.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime3-300x142.png" alt="Facebook Timeline Movie" title="Facebook Timeline Movie" width="300" height="142" class="size-medium wp-image-2792" /></a><p class="wp-caption-text">Facebook Timeline Movie</p></div>  <div id="attachment_2793" class="wp-caption alignleft" style="width: 276px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime2.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime2-266x300.png" alt="Facebook Timeline Movie" title="Facebook Timeline Movie" width="266" height="300" class="size-medium wp-image-2793" /></a><p class="wp-caption-text">Facebook Timeline Movie</p></div></p>
<h2>Achievement and Scores API</h2>
<p>Facebook provides with some special timeline api&#8217;s for game app&#8217;s. If your app category is selected as &#8216;Game&#8217;, then you can use these 2 api&#8217;s in your app.</p>
<p>Here is the <a href="http://developers.facebook.com/blog/post/539/" title="Facebook Achievement and Score" target="_blank">office blog</a> provided by facebook on publishing scores and achievements. </p>
<p>To publish it the code is explain below</p>
<p>1. You need generated an app access token</p>
<pre class="brush: php; title: ; notranslate">
$app_id = 'XXXX';
$app_secret = 'XXXXXX';
// Get an App Access Token
$token_url = 'https://graph.facebook.com/oauth/access_token?'
	. 'client_id=' .$app_id
	. '&amp;client_secret='.$app_secret
	. '&amp;grant_type=client_credentials';

 $token_response = file_get_contents($token_url);
 $params = null;
 parse_str($token_response, $params);
 $app_access_token = $params['access_token'];
</pre>
<p>2. You need to register an achievement. You can read more details about <a href="https://developers.facebook.com/docs/achievements/" title="Facebook Achievements " target="_blank">achievements here</a> as it has many restrictions. </p>
<pre class="brush: php; title: ; notranslate">
$achievement = 'http://excellencetechnologies.co.in/fb/achievement.php?id='.rand(0,100);
print('Register a User Achievement&lt;br/&gt;');
$achievement_display_order = 1;
$achievement_registration_URL = 'https://graph.facebook.com/'.$app_id.'/achievements';
$achievement_registration_result=https_post($achievement_registration_URL,
	'achievement=' . $achievement
        . '&amp;display_order=' . $achievement_display_order
	. '&amp;access_token=' . $app_access_token
 );
</pre>
<p>3. In the achievement.php file you need add this code</p>
<pre class="brush: php; title: ; notranslate">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head prefix=&quot;og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#&quot;&gt;
  
  &lt;meta property=&quot;fb:app_id&quot;      content=&quot;APP_ID&quot; /&gt; 
  &lt;meta property=&quot;og:type&quot;        content=&quot;game.achievement&quot; /&gt; 
  &lt;meta property=&quot;og:url&quot;         content=&quot;http://excellencetechnologies.co.in/fb/achievement.php?id=&lt;?php echo $_REQUEST['id'] ?&gt;&quot; /&gt; 
  &lt;meta property=&quot;og:image&quot;                content=&quot;http://ia.media-imdb.com/images/M/MV5BMTc3NzQ3OTg3NF5BMl5BanBnXkFtZTcwMjk5OTcxNw@@._V1._SY317_.jpg&quot;&gt;
  &lt;meta property=&quot;og:title&quot;                content=&quot;Game Points Test&quot;&gt;
  &lt;meta property=&quot;og:description&quot;          content=&quot;Game Points Test&quot;&gt;
  &lt;meta property=&quot;game:points&quot; content=&quot;100&quot; /&gt;
 
&lt;/head&gt;
&lt;body class=&quot;index&quot;&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>4. Finally publish a user achievement </p>
<pre class="brush: php; title: ; notranslate">
print('Publish a User Achievement&lt;br/&gt;');
$achievement_URL = 'https://graph.facebook.com/'.$user_profile['id'].'/achievements';
	  $achievement_result = https_post($achievement_URL,
	'achievement=' . $achievement
	. '&amp;access_token=' . $app_access_token
  );
 print('&lt;br/&gt;&lt;br/&gt;');
</pre>
<p>This is how an achievement looks when published<br />
<div id="attachment_2805" class="wp-caption alignleft" style="width: 246px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime1.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime1-236x300.png" alt="Facebook Achievements" title="Facebook Achievements" width="236" height="300" class="size-medium wp-image-2805" /></a><p class="wp-caption-text">Facebook Achievements</p></div>  <div id="attachment_2806" class="wp-caption alignleft" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime5.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fbtime5-300x81.png" alt="Facebook Achievements" title="Facebook Achievements" width="300" height="81" class="size-medium wp-image-2806" /></a><p class="wp-caption-text">Facebook Achievements</p></div></p>
<div style='clear:both'></div>
<p>I got few errors before i was able to publish achievements<br />
<i>Error1: (#3) Method allowed only for games</i><br />
Solution: Your app should have category as &#8216;Game&#8217;</p>
<p><i>Error2: This method must be called with an app access_token.</i><br />
Solution: A valid app access token should be generated using the above method. App access token is different from the normal access token.</p>
<p><i>Error3:<br />
{&#8220;error&#8221;:{&#8220;message&#8221;:&#8221;(#3502) Object at achievement URL is not of type game.achievement&#8221;,&#8221;type&#8221;:&#8221;OAuthException&#8221;,&#8221;code&#8221;:3502}}</i><br />
Solution: the og:type property is set wrongly in achievement.php file. it should be game.achievement </p>
<p>If you want to <b>publish score</b> for a user you need do the below.</p>
<pre class="brush: php; title: ; notranslate">
$score = 1;
 // POST a user score
 print('Publish a User Score&lt;br/&gt;');
  $score_URL = 'https://graph.facebook.com/' . $user_profile['id'] . '/scores';
  $score_result = https_post($score_URL,
'score=' . $score . '&amp;access_token=' . $app_access_token
 );
 print('&lt;br/&gt;&lt;br/&gt;');
</pre>
<p>you can create more about <a href="http://developers.facebook.com/docs/score/" title="Facebook Scores" target="_blank">scores here</a>. </p>
<p>Attached is the source code<br />
<div class='facebook-download'>
<table border="0" cellpadding="3" width="80%" class='noauth'>
  <tr>
    <td width="10%" style="text-align:center" valign='top'  class='image'>
      <img src="http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/fb_nouser.jpg" alt="#twitter#" width="48px" height="48px">
    </td>
    <td width="60%" valign='top' style='padding-top: 13px !important;'>
    	<b>Download: </b><span class='name'>Facebook Timeline PHP</span><small>(19.47KB)</small>
    	<span style="padding-left:20px"><b>Clicks: </b>172</span>
    	<br />
      	Login via <a onclick='login();return false;' href='#'>facebook</a> to download the file!
      	<br/>
      	<div style='float:left'>
      	<a onclick='login();return false;' href='#'><img src='http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/facebook_login.jpg' alt='facebook login'/></a>
      	</div>
      	<div style='float:left;margin-top: 3px;margin-left: 6px;'>
      	<small>By logging in you agree to subscribe to our montly newsletter as well.</small>
      	</div>
      	<div style='clear:both'></div>
      </td>
  </tr>
</table>
</div></p>
<img src="http://feeds.feedburner.com/~r/etech-blog/~4/McSXkBVkD0M" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.excellencemagentoblog.com/facebook-timeline-app-built-in-actions-objects-scores-achievements/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.excellencemagentoblog.com/facebook-timeline-app-built-in-actions-objects-scores-achievements?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=facebook-timeline-app-built-in-actions-objects-scores-achievements</feedburner:origLink></item>
		<item>
		<title>Facebook App and Timeline Integration (Actions, Objects and Aggregations)</title>
		<link>http://feedproxy.google.com/~r/etech-blog/~3/D5SNZKUMfxw/facebook-app-and-timeline-integration-action-objects-aggregations</link>
		<comments>http://www.excellencemagentoblog.com/facebook-app-and-timeline-integration-action-objects-aggregations#comments</comments>
		<pubDate>Fri, 23 Mar 2012 08:56:21 +0000</pubDate>
		<dc:creator>Manish Prakash</dc:creator>
				<category><![CDATA[Facebook]]></category>
		<category><![CDATA[facebbok]]></category>

		<guid isPermaLink="false">http://www.excellencemagentoblog.com/?p=2679</guid>
		<description><![CDATA[In this tutorial we will see how to integrate your &#8230; <a href="http://www.excellencemagentoblog.com/facebook-app-and-timeline-integration-action-objects-aggregations"> <span class="meta-nav"></span></a>]]></description>
			<content:encoded><![CDATA[<div class='inter'>In this tutorial we will see how to integrate your facebook app with user&#8217;s timeline. Facebook has recently introduced this feature, i.e apps have permission to publish information on user timeline.</div>
<p> This is a very powerful feature which facebook has provided and is very useful to virally spread your application. <span id="more-2679"></span></p>
<p><small><i>This is an advanced facebook tutorial, so you should be familiar with based facebook integration first. </i></small><br />
To given an idea of what you can do with timeline integration read below</p>
<ul>
<li>Any action performed by user on your can be published to his timeline e.g if a user reads a blog, using app it can be published in the user timeline that he read a blog post.</li>
<li>You can create custom action&#8217;s and object&#8217;s depending on your website e.g User <i>voted</i> for a <i>College</i>, User <i>read</i> a </i>Article</i>, User <i>participated</i> in a </i>Quiz</i>. Here text written in italics are actions and objects respectively, and we can custom action,object as many as we want.</li>
</ul>
<p>Attached is a screenshot of the it look on timeline, this was published on timeline by an app created by me on <a href="http://www.collegekhabar.com/ranking">www.collegekhabar.com/ranking</a><br />
<div id="attachment_2687" class="wp-caption aligncenter" style="width: 269px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline1.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline1-259x300.png" alt="Timeline App Integration" title="Timeline App Integration" width="259" height="300" class="size-medium wp-image-2687" /></a><p class="wp-caption-text">Timeline App Integration</p></div></p>
<div class='title'>Basic of timeline integration &#8211; Action, Object, Aggregation </div>
<p>There are few terms which are used when doing timeline integration. I will just explain them in brief here, using the sentences below<br />
 User <i>voted</i> for a <i>College</i><br />
 User <i>read</i> a </i>Article</i><br />
 User <i>participated</i> in a </i>Quiz</i><br />
<b>Action:</b>: Action is basically an adjective like in above cases vote, read, participated are actions. <a href="http://developers.facebook.com/docs/opengraph/define-actions/" title="Facebook Timeline Actions" target="_blank">Read more here</a><br />
<b>Object</b>: The entity on which actions are performed are called objects, like in above sentences College, Article, Quiz are objects. <a href="http://developers.facebook.com/docs/opengraph/define-objects/" title="Facebook Timeline Objects" target="_blank">Read more here</a><br />
<b>Aggregation:</b> This basically is used to define the display of how it will look in a user timeline when a user performs multiple actions on a object.  <a href="http://developers.facebook.com/docs/opengraph/define-units/" title="Facebook Timeline Aggregation" target="_blank">Read more here</a></p>
<div class='title'>Developing timeline application</div>
<p>Now lets see in detail what are all the steps to follow to develop a timeline application.</p>
<p>First step is to <a href="http://www.excellencemagentoblog.com/magento-facebook-integration-facebook-page-and-apps" target="_blank">create a basic facebook app</a> and set it up on your domain.</p>
<p>Next you need to add this app to your website so that user can authenticate your app to publish actions to their timeline. To do this you need to put the facebook login button, as discussed in <a href="http://www.excellencemagentoblog.com/facebook-login-integration-website" title="Facebook Login" target="_blank">the previous tutorial</a>.<br />
But this time in our app permission we will add &#8216;publish_actions&#8217; permission to our app scope. So basically our app scope would look like </p>
<pre class="brush: php; title: ; notranslate">
{scope:'email,publish_actions'}
</pre>
<p>Only after user has given permission to our app with &#8216;publish_actions&#8217; scope can we publish actions to his profile. </p>
<p>Next we we need to define our custom actions and object to use in our application. To do this open your app in facebook developer website, and click on Edit Open Graph.<br />
<div id="attachment_2712" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline2.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline2-300x198.png" alt="Facebook App Edit Open Graph" title="Facebook App Edit Open Graph" width="300" height="198" class="size-medium wp-image-2712" /></a><p class="wp-caption-text">Facebook App Edit Open Graph</p></div></p>
<p>After you click on edit open graph, you will get a message from facebook to setup the app namespace.<br />
<div id="attachment_2715" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline3.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline3-300x98.png" alt="Facebook Set App Namespace" title="Facebook Set App Namespace" width="300" height="98" class="size-medium wp-image-2715" /></a><p class="wp-caption-text">Facebook Set App Namespace</p></div><br />
Just go to the app summary page and set a unique app namespace. Remember this app namespace, as it will be required in all future api calls. I my case i have set my app namespace as &#8216;etechblog&#8217;.</p>
<p>Now again go back to the &#8216;Edit Open Graph&#8217; page, here you need to setup your action and object. Now you will see a page where facebook asks you enter the action and object in a sentence. In my case, i have take action = &#8216;download&#8217; and object = &#8216;module&#8217;.<br />
<div id="attachment_2719" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline4.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline4-300x115.png" alt="Facebook Create Action" title="Facebook Create Action" width="300" height="115" class="size-medium wp-image-2719" /></a><p class="wp-caption-text">Facebook Create Action</p></div><br />
After doing this click on &#8216;Get Started&#8217; green button and facebook will create your action and object. In the next page you will see, facebook asks for more details about the action  created. You can see details about this page <a href="http://developers.facebook.com/docs/opengraph/define-actions/" title="Facebook Actions" target="_blank">here</a><br />
Every thing is pre-filled in by default, so you can simple click on &#8216;Save Changes and Next&#8217;. The next page asks for details about the object created, <a href="http://developers.facebook.com/docs/opengraph/define-objects/" title="Facebook Objects" target="_blank">read more here for details</a>. After click on &#8216;Save Changes and Next&#8217;, the last page which shows up asks for details of the aggregation. You can read more about it <a href="http://developers.facebook.com/docs/opengraph/define-units/" title="Facebook Aggregation" target="_blank">here</a>. Finally after finishing these steps you see a page like this<br />
<div id="attachment_2722" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline5.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline5-300x174.png" alt="Facebook Action, Object and Aggregation" title="Facebook Action, Object and Aggregation" width="300" height="174" class="size-medium wp-image-2722" /></a><p class="wp-caption-text">Facebook Action, Object and Aggregation</p></div></p>
<p>Next lets see how to publish user actions to his timeline from our website.<br />
<b>Its important to note here that the custom action you created cannot be directly published to users timeline. What i mean is that before being able to publish user actions, you need to approve your actions from facebook. But to initially to test your actions, the action will get published on your personal facebook account only from where you have created the app.</b></p>
<p>To submit your action to facebook for approval you need to click on the &#8216;Submit&#8217; link in front of the action and follow their submission process. It took me about <u>2weeks time to get by action approved</u> so please bear this in mind during development.<br />
<div id="attachment_2730" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline6.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline6-300x175.png" alt="Facebook Submit Action" title="Facebook Submit Action" width="300" height="175" class="size-medium wp-image-2730" /></a><p class="wp-caption-text">Facebook Submit Action</p></div></p>
<p>Now to publish an action, it can be done through php, javascript, facebook php-sdk and many  other ways. But its important to remember that you should have a authenticated user access token to publish the actions, this basically means user should have approved your app for timeline access.</p>
<p>Code to publish through facebook php-sdk</p>
<pre class="brush: php; title: ; notranslate">
try{
$params = array('module'=&gt;'www.websiteurl.com/page.php?id=3');
$out = $facebook-&gt;api('/me/etechblog:download','post',$params);
}catch(Exception $e){
echo $e-&gt;getMessage();
}
</pre>
<p>Code to publish through facebook javascript-sdk</p>
<pre class="brush: php; title: ; notranslate">
FB.api('/me/etechblog:download', 'post', 
  { module : 'www.websiteurl.com/page.php?id=3' });
</pre>
<p>You can see more details of the <a href="http://developers.facebook.com/docs/opengraph/actions/" title="Publish Actions" target="_blank">above code here</a> </p>
<p>Next important part, the url which we passed www.websiteurl.com/page.php?id=3. We need to setup meta tags in this page to set all properties of the object.  In the file page.php you need add code like this</p>
<pre class="brush: php; title: ; notranslate">
&lt;head prefix=&quot;og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# collegekhabar_etech: http://ogp.me/ns/fb/collegekhabar_etech#&quot;&gt;
  &lt;?php if(isset($_REQUEST['id'])) { 
  $info = $my_obj-&gt;getCompleteDetails($_REQUEST['collage']); ?&gt;
  &lt;meta property=&quot;fb:app_id&quot;      content=&quot;XXXX&quot; /&gt;  &lt;!-- APP ID --&gt;
  &lt;meta property=&quot;og:type&quot;        content=&quot;etechblog:module&quot; /&gt;  &lt;!-- app namespace:object --&gt; 
  &lt;meta property=&quot;og:url&quot;         content=&quot;www.websiteurl.com/page.php?id=&lt;?php echo $_REQUEST['id'] ?&gt;&quot; /&gt; &lt;!-- same as the url passed while publishing the action --&gt;
  &lt;meta property=&quot;og:title&quot;       content=&quot;&lt;?php echo $info[0]['collage_short']?&gt;&quot; /&gt; &lt;!-- get title from database --&gt;
  &lt;meta property=&quot;og:description&quot; content=&quot;&lt;?php echo $info[0]['collage_name']?&gt;&quot; /&gt; &lt;!-- get description from database --&gt;
  &lt;meta property=&quot;og:image&quot;       content=&quot;http://www.collegekhabar.com/ranking/ranking/&lt;?php echo $info[0]['logo']?&gt;&quot; /&gt; 
&lt;!-- get image from database --&gt;
  &lt;?php } else { ?&gt;  &lt;!-- Else condition required to prevent any errors --&gt;
  &lt;meta property=&quot;fb:app_id&quot;      content=&quot;XXXXX&quot; /&gt; 
  &lt;meta property=&quot;og:type&quot;        content=&quot;etechblog:module&quot; /&gt; 
  &lt;meta property=&quot;og:url&quot;         content=&quot;www.websiteurl.com&quot; /&gt; 
  &lt;meta property=&quot;og:title&quot;       content=&quot;title&quot; /&gt; 
  &lt;meta property=&quot;og:description&quot; content=&quot;description&quot; /&gt; 
  &lt;meta property=&quot;og:image&quot;       content=&quot;images/logo.png&quot; /&gt; 
  &lt;?php } ?&gt;
</pre>
<p>The meta properties that you need to define comes from the object properties which you define when creating an object. Attached here is the screenshot from where you can add properties, also get the meta property name and value.<br />
<div id="attachment_2739" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline7.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline7-300x155.png" alt="Facebook Timeline Object Properties" title="Facebook Timeline Object Properties" width="300" height="155" class="size-medium wp-image-2739" /></a><p class="wp-caption-text">Facebook Timeline Object Properties</p></div></p>
<p>Here there is a very important thing to notice, the url given in &lt;meta property=&#8221;og:url&#8221; /&gt; is from where facebook will read the meta tags and not from the url given when publishing an action. You can also check the meta tags facebook is reading from your URL from <a href="http://developers.facebook.com/tools/debug" target="_blank">http://developers.facebook.com/tools/debug</a>. Just put your page URL in the debugger and press debug, it will show the tags facebook is able to read.<br />
<div id="attachment_2742" class="wp-caption aligncenter" style="width: 272px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline8.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/timeline8-262x300.png" alt="Facebook Debugger" title="Facebook Debugger" width="262" height="300" class="size-medium wp-image-2742" /></a><p class="wp-caption-text">Facebook Debugger</p></div></p>
<p>Facebook debugger is generally a useful tool, it can also be used to refersh the facebook cache for a particular url. </p>
<div class='end'>I think i have covered everything in this tutorial, from creating action,objects to publishing them.</div>
<img src="http://feeds.feedburner.com/~r/etech-blog/~4/D5SNZKUMfxw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.excellencemagentoblog.com/facebook-app-and-timeline-integration-action-objects-aggregations/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		<feedburner:origLink>http://www.excellencemagentoblog.com/facebook-app-and-timeline-integration-action-objects-aggregations?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=facebook-app-and-timeline-integration-action-objects-aggregations</feedburner:origLink></item>
		<item>
		<title>Facebook Login Integration on Website</title>
		<link>http://feedproxy.google.com/~r/etech-blog/~3/pXJnggNdmxo/facebook-login-integration-website</link>
		<comments>http://www.excellencemagentoblog.com/facebook-login-integration-website#comments</comments>
		<pubDate>Thu, 22 Mar 2012 13:11:37 +0000</pubDate>
		<dc:creator>Manish Prakash</dc:creator>
				<category><![CDATA[Facebook]]></category>
		<category><![CDATA[facebook]]></category>

		<guid isPermaLink="false">http://www.excellencemagentoblog.com/?p=2616</guid>
		<description><![CDATA[In this tutorial we will see how to integrate facebook &#8230; <a href="http://www.excellencemagentoblog.com/facebook-login-integration-website"> <span class="meta-nav"></span></a>]]></description>
			<content:encoded><![CDATA[<div class='intro'>In this tutorial we will see how to integrate facebook login on your website. This is useful because user&#8217;s can easliy create account through facebook instead of filling up the registration form, so it makes registration and login faster.</div>
<p> This tutorial is not related to magento, but rather just focuses on facebook api&#8217;s. <span id="more-2616"></span> There are many tutorial&#8217;s available online on this topic, but i personally had a tough time figuring out the correct method to use. So i am writing down here the best method which i found out.</p>
<div class='title'>Facebook Login and Authentication</div>
<p>Facebook provides an authentication api which you can use as an alternate for the traditional login system or also to import facebook user profile information to your website. Basically how this works is you create a facebook app, ask user to grant permission to your app to access his profile information, after he has granted access you can create account on your website using his profile information.<br />
This is the workflow which gets followed when integrating facebook login on your site (helpful for a beginner) </p>
<ul>
<li>Create a facebook app for your domain</li>
<li>Place a login button on your website</li>
<li>
When user clicks on the login button there conditions are possible.</p>
<div style='padding-left:20px'>
1. <b>User is Not Logged In</b>: Facebook dialog pop&#8217;s up and asks user to login. <div id="attachment_2653" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fblogin1.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fblogin1-300x182.png" alt="Facebook Login Box" title="Facebook Login Box" width="300" height="182" class="size-medium wp-image-2653" /></a><p class="wp-caption-text">Facebook Login Box</p></div><br />
2. <b>User is Logged In, but has not authorized the app</b>: Facebook pop&#8217;s up a dialog asking user to give permission to your app. <div id="attachment_2655" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fblogin2.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2012/03/fblogin2-300x197.png" alt="Facebook Authorization Dialog" title="Facebook Authorization Dialog" width="300" height="197" class="size-medium wp-image-2655" /></a><p class="wp-caption-text">Facebook Authorization Dialog</p></div><br />
3. <b>User is Logged In and has already authorized the app</b><br />
In this case, facebook will directly redirect to a page specified by us.
</div>
<li>
On the page where facebook redirects, we retrieve user information like name, email, facebook id etc and create his account on our website.
</li>
</li>
</ul>
<p>The entire code is divided in two part<br />
1. javascript<br />
2. php</p>
<p>Below is the java script code to be applied</p>
<pre class="brush: php; title: ; notranslate">
&lt;div id=&quot;fb-root&quot;&gt;&lt;/div&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
//&lt;![CDATA[
window.fbAsyncInit = function() {
   FB.init({
     appId      : 'XXXXXXXXXXXXXX', // App ID
     channelURL : '', // Channel File, not required so leave empty
     status     : true, // check login status
     cookie     : true, // enable cookies to allow the server to access the session
     oauth      : true, // enable OAuth 2.0
     xfbml      : false  // parse XFBML
   });
};
// logs the user in the application and facebook
function login(){
FB.getLoginStatus(function(r){
	 if(r.status === 'connected'){
        	window.location.href = 'fbconnect.php';
	 }else{
		FB.login(function(response) {
	        	if(response.authResponse) {
			  //if (response.perms) 
		        	window.location.href = 'fbconnect.php';
			} else {
			  // user is not logged in
			}
	 },{scope:'email'}); // which data to access from user profile
 }
});
}
// Load the SDK Asynchronously
(function() {
   var e = document.createElement('script'); e.async = true;
   e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';  		       
   document.getElementById('fb-root').appendChild(e);
}());
//]]&gt;
&lt;/script&gt;
</pre>
<p>The above code is divided in three parts<br />
<b>Part1</b></p>
<pre class="brush: php; title: ; notranslate">
&lt;div id=&quot;fb-root&quot;&gt;&lt;/div&gt;

// Load the SDK Asynchronously
(function() {
   var e = document.createElement('script'); e.async = true;
   e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';  		       
   document.getElementById('fb-root').appendChild(e);
}());
</pre>
<p>This code simply add the facebook library javascript to the page, it appends it to the &#8216;fb-root&#8217; element.<br />
<b>Part2</b></p>
<pre class="brush: php; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot;&gt;

window.fbAsyncInit = function() {
   FB.init({
     appId      : 'XXXXXXXXXXXXXX', // App ID
     channelURL : '', // Channel File, not required so leave empty
     status     : true, // check login status
     cookie     : true, // enable cookies to allow the server to access the session
     oauth      : true, // enable OAuth 2.0
     xfbml      : false  // parse XFBML
   });
};
</pre>
<p>This code initializes FB object. In the appID you need to provide your application id of the app you created on facebook.<br />
<i>Keep the parameters &#8216;status&#8217; = true. On making this false, i have noticed in the internet explorer that problem arises with popup blocker.</i><br />
<b>Part3</b></p>
<pre class="brush: php; title: ; notranslate">
function login(){
FB.getLoginStatus(function(r){ //check if user already authorized the app
	 if(r.status === 'connected'){
        	window.location.href = 'fbconnect.php';
	 }else{
		FB.login(function(response) { // opens the login dialog
	        	if(response.authResponse) { // check if user authorized the app
			  //if (response.perms) {
		        	window.location.href = 'fbconnect.php';
			} else {
			  // user is not logged in
			}
	 },{scope:'email'}); //permission required by the app
 }
});
}
</pre>
<p>This function needs to be added to an onclick event on any html element. e.g you can have an image and on clicking on that image you want the facebook login box to open. In that case you need to call the login() function on its on click event.</p>
<pre class="brush: php; title: ; notranslate">
&lt;a href='#' onclick='login();'&gt;Facebook Login&lt;/a&gt;
</pre>
<p>Next in the php file i.e fbconnect.php we need to add code to retrieve facebook user profile details. We need facebook php-sdk for this purpose which can be downloaded from <a href="https://github.com/facebook/php-sdk" target='_blank'>https://github.com/facebook/php-sdk</a></p>
<pre class="brush: php; title: ; notranslate">
require_once 'src/facebook.php'; //include the facebook php sdk
$facebook = new Facebook(array(
		'appId'  =&gt; 'XXXXXXXXXXXXXX',    //app id
		'secret' =&gt; 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX', // app secret
));
$user = $facebook-&gt;getUser(); 
if ($user) { // check if current user is authenticated
	try {
		// Proceed knowing you have a logged in user who's authenticated.
		$user_profile = $facebook-&gt;api('/me');  //get current user's profile information using open graph
            }
         catch(Exception $e){}
}
</pre>
<p>The varaible $user_profile will contain the profile information of the user like firstname, lastname, email, facebook id etc. You can use this information to create his account on your website.</p>
<p>The content of the $user_profile depends on the permission which we have asked in the app. There permission are set in &#8216;scope&#8217; parameter in our javascript code. A full list of all facebook permissions are given <a href="http://developers.facebook.com/docs/authentication/permissions/" title="Facebook App Permissions" target="_blank">here</a></p>
<img src="http://feeds.feedburner.com/~r/etech-blog/~4/pXJnggNdmxo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.excellencemagentoblog.com/facebook-login-integration-website/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		<feedburner:origLink>http://www.excellencemagentoblog.com/facebook-login-integration-website?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=facebook-login-integration-website</feedburner:origLink></item>
		<item>
		<title>Magento Facebook Integration – Facebook Page and Apps</title>
		<link>http://feedproxy.google.com/~r/etech-blog/~3/fOkLaRXhFWY/magento-facebook-integration-facebook-page-and-apps</link>
		<comments>http://www.excellencemagentoblog.com/magento-facebook-integration-facebook-page-and-apps#comments</comments>
		<pubDate>Fri, 02 Mar 2012 05:44:28 +0000</pubDate>
		<dc:creator>Manish Prakash</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[facebook]]></category>

		<guid isPermaLink="false">http://www.excellencemagentoblog.com/?p=1879</guid>
		<description><![CDATA[In this tutorial we are going to see how to &#8230; <a href="http://www.excellencemagentoblog.com/magento-facebook-integration-facebook-page-and-apps"> <span class="meta-nav"></span></a>]]></description>
			<content:encoded><![CDATA[<div class='intro'>In this tutorial we are going to see how to show a magento page inside facebook page tab. An application of this would be, if you want to show few of your magento products inside facebook page.</div>
<p> In the current tutorial we will create a facebook page which will display a different content for like page and unlike page, the content of the like/unlike page will come from a magento module. <span id="more-1879"></span><br />
This is easy to implement, we don&#8217;t need to have any knowledge of facebook api&#8217;s. Facebook provides an interface through which we can simply integrate any iframe page in a facebook page tab. We are going to use the iframe based system to show magento page inside the iframe. To implement this first we need to create a facebook page, register a developer account and then create a facebook app. I will explain here in detail what are all the steps to follow. </p>
<div class='title'>Step1: Create a Facebook Page</div>
<p>Creating a new page is very easy in facebook. Just login with your facebook account and open this <a href="http://www.facebook.com/pages/create.php" title="Facebook Page" target="_blank">URL to create a page</a>. Here you can find more details about a facebook page <a href="http://www.facebook.com/pages/learn.php" title="Facebook Page" target="_blank">http://www.facebook.com/pages/learn.php</a>.</p>
<div class='title'>Step2: Create a Facebook App</div>
<p>After you have created a facebook page, you need to create a facebook app. For creating a facebook app you need first have a developer account in facebook. Developer account is very easy to create just open the <a href="http://developers.facebook.com/" title="http://developers.facebook.com/" target="_blank">URL </a> and then click on &#8220;Apps&#8221; in the top menu. After clicking on &#8220;Apps&#8221; your are asked to authorize the &#8220;Developer App&#8221;. After you authorize this your developer account is created (attached is screenshot of the same) <div id="attachment_2539" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb-300x140.png" alt="Facebook Developer App" title="Facebook Developer App " width="300" height="140" class="size-medium wp-image-2539" /></a><p class="wp-caption-text">Facebook Developer App </p></div> After granting permission your able to view a screen where you can create new apps. <div id="attachment_2543" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb2.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb2-300x39.png" alt="Facebook Create App" title="Facebook Create App" width="300" height="39" class="size-medium wp-image-2543" /></a><p class="wp-caption-text">Facebook Create App</p></div> Next you need to click on &#8220;Create New App&#8221; button as shown in screenshot to create an app, you will have put it the app name you want and fill in a captcha. After creating an app you will get a form to fill in app details like shown below <div id="attachment_2547" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb3.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb3-300x221.png" alt="Facebook Empty App" title="Facebook Empty App" width="300" height="221" class="size-medium wp-image-2547" /></a><p class="wp-caption-text">Facebook Empty App</p></div> In the &#8220;App Domain&#8221; field you need to enter your magento website domain name e.g excellencemagentoblog.com. Next, in the section &#8220;Select how your app integrates with Facebook&#8221; you need to put in information in boxes &#8220;Website&#8221; and &#8220;Page Tab&#8221;. In <b>&#8220;Website&#8221; -> &#8220;Site URL&#8221;</b> you need to put in your full magento website url. In the <b>&#8220;Page Tab&#8221; -> &#8220;Page Tab Name&#8221;</b> put in the name of the tab, <b>&#8220;Page Tab&#8221; -> &#8220;Page Tab URL&#8221;</b> will have the url of the magento module which we will show in the facebook page. In our case the URL would be www.yourmagentostoreurl.com/fb (here &#8216;fb&#8217; is the fronend name of the custom module create by us). Attached is exactly how the app setting needs to be done <div id="attachment_2550" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb4.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb4-300x191.png" alt="Facebook App Settings" title="Facebook App Settings" width="300" height="191" class="size-medium wp-image-2550" /></a><p class="wp-caption-text">Facebook App Settings</p></div> Also attached here the facebook magento module developed, will explain this module in detail later<br />
<div class='facebook-download'>
<table border="0" cellpadding="3" width="80%" class='noauth'>
  <tr>
    <td width="10%" style="text-align:center" valign='top'  class='image'>
      <img src="http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/fb_nouser.jpg" alt="#twitter#" width="48px" height="48px">
    </td>
    <td width="60%" valign='top' style='padding-top: 13px !important;'>
    	<b>Download: </b><span class='name'>FB Module</span><small>(18.48KB)</small>
    	<span style="padding-left:20px"><b>Clicks: </b>244</span>
    	<br />
      	Login via <a onclick='login();return false;' href='#'>facebook</a> to download the file!
      	<br/>
      	<div style='float:left'>
      	<a onclick='login();return false;' href='#'><img src='http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/facebook_login.jpg' alt='facebook login'/></a>
      	</div>
      	<div style='float:left;margin-top: 3px;margin-left: 6px;'>
      	<small>By logging in you agree to subscribe to our montly newsletter as well.</small>
      	</div>
      	<div style='clear:both'></div>
      </td>
  </tr>
</table>
</div></p>
<div class='title'>Step3: Assign facebook app to page tab</div>
<p>In this step we will attach the facebook app we created to a facebook page tab. What this means is that, when a person opens the facebook like page our facebook app will load on that page instead of the default page tabs. To do this first we need to assign the app created to a facebook page, for that you need to open this URL</p>
<pre class="brush: plain; title: ; notranslate">

https://www.facebook.com/dialog/pagetab?app_id=YOUR_APP_ID&#038;next=YOUR_URL

</pre>
<p>here you need to replace &#8220;YOUR_APP_ID&#8221; with your app id which can be found the edit app page, and replace &#8220;YOUR_URL&#8221; with the application site url. After you do this you will get a screen like this <div id="attachment_2563" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb5.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb5-300x118.png" alt="Facebook Add App To Page" title="Facebook Add App To Page" width="300" height="118" class="size-medium wp-image-2563" /></a><p class="wp-caption-text">Facebook Add App To Page</p></div> On this box, from the dropdown you need to select the page you have created. After doing this, open the page created and then click on &#8220;Edit Page&#8221; and then &#8220;Apps&#8221; on the left menu. After clicking on &#8220;Apps&#8221; on the content area you will see the app we just added. Attached is screenshot of the page<div id="attachment_2569" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb61.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb61-300x154.png" alt="Facebook Page" title="Facebook Page" width="300" height="154" class="size-medium wp-image-2569" /></a><p class="wp-caption-text">Facebook Page</p></div> This means, the facebook app has been successfully added to the page. Next we need to assign this app to a page tab. For this, click on the &#8220;Edit Settings&#8221; link and you will see a screen where you can enter the name of of the tab (attach is screen). <div id="attachment_2571" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb7.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb7-300x165.png" alt="Facebook App Name" title="Facebook App Name" width="300" height="165" class="size-medium wp-image-2571" /></a><p class="wp-caption-text">Facebook App Name</p></div> After doing this open the page. it will show the tab created and clicking on the tab will load our magento page. <div id="attachment_2573" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb8.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb8-300x209.png" alt="Facebook Page New Tab" title="Facebook Page New Tab" width="300" height="209" class="size-medium wp-image-2573" /></a><p class="wp-caption-text">Facebook Page New Tab</p></div> If you want this to be the default tab to load when a person opens the facebook page, you can do the setting from Facebook Edit Page -&gt; Manage Permissions -&gt; Default Landing Tab <div id="attachment_2574" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb9.png"><img src="http://www.excellencemagentoblog.com/wp-content/uploads/2011/10/fb9-300x164.png" alt="Facebook Page Default Tab" title="Facebook Page Default Tab" width="300" height="164" class="size-medium wp-image-2574" /></a><p class="wp-caption-text">Facebook Page Default Tab</p></div> </p>
<div class='title'>Step4: Magento Module</div>
<p>Above we have seen what all is required to be done on facebook side, now we will see what needs to be done in magneto. I am again attaching here the module used.<br />
<div class='facebook-download'>
<table border="0" cellpadding="3" width="80%" class='noauth'>
  <tr>
    <td width="10%" style="text-align:center" valign='top'  class='image'>
      <img src="http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/fb_nouser.jpg" alt="#twitter#" width="48px" height="48px">
    </td>
    <td width="60%" valign='top' style='padding-top: 13px !important;'>
    	<b>Download: </b><span class='name'>FB Module</span><small>(18.48KB)</small>
    	<span style="padding-left:20px"><b>Clicks: </b>244</span>
    	<br />
      	Login via <a onclick='login();return false;' href='#'>facebook</a> to download the file!
      	<br/>
      	<div style='float:left'>
      	<a onclick='login();return false;' href='#'><img src='http://www.excellencemagentoblog.com/wp-content/themes/excelltheme/images/facebook_login.jpg' alt='facebook login'/></a>
      	</div>
      	<div style='float:left;margin-top: 3px;margin-left: 6px;'>
      	<small>By logging in you agree to subscribe to our montly newsletter as well.</small>
      	</div>
      	<div style='clear:both'></div>
      </td>
  </tr>
</table>
</div><br />
What the module does is very simple, it shows a different text for page when its liked and when its not liked.  In the index controller of the module i have written an indexAction() which simply loads layout and renders it. The code to show a different text for like page and unlike page is written in the block class. </p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
class Excellence_Fb_Block_Fb extends Mage_Core_Block_Template
{
	protected function _construct()
	{
		parent::_construct();
		$signed_request =$this-&gt;parsePageSignedRequest();// Call function

		/*The signed_request on iframe tabs has a &quot;pages&quot; object, which holds a &quot;liked&quot; variable. If the user    viewing your tab has Liked your page, it is set to TRUE. If they have not, it is set to FALSE. So:
		 */
		if($signed_request['page']['liked']){
			$this-&gt;setTemplate('fb/like.phtml');
		} else{
			$this-&gt;setTemplate('fb/unlike.phtml');
		}
	}
	public function parsePageSignedRequest() {  //The signed request is encoded for security
		$facebook = Mage::getModel('fb/api_facebook');
		$signed_request = $facebook-&gt;getSignedRequest();
		return $signed_request;
	}
}
</pre>
<p>Here i am using the php facebook sdk in magento, and based the api finding out if the facebook user has liked the page or not. If the page is liked, the fb/like.php is set as template or else fb/unlike.phtml is set as the template. </p>
<div class='title'>Step5: Resize of Facebook Page</div>
<p>If you have long content inside the facebook like.phtml or unlike.phtml, you will see that scrollbars show up in the facebook page tab. To fix the problem of vertical scroll bar showing up you need to put in this code the template files</p>
<pre class="brush: php; title: ; notranslate">
&lt;div id=&quot;fb-root&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;http://connect.facebook.net/en_US/all.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt; 
      FB.init({
        appId  : 'YOUR_APPLICATION_ID',
        oauth  : true,
      });
 
      FB.Canvas.setAutoGrow();
 
&lt;/script&gt; 
</pre>
<p>this will fix the vertical scroll bar problem.</p>
<div class='end'>In this tutorial i have tried my best on how to integrate facebook and magento module. The process is quite simple, another blog which i found usefully is <a href="http://www.hyperarts.com/blog/tutorial-add-an-iframe-application-to-your-facebook-fan-page-fall-2012/" target="_blank">http://www.hyperarts.com/blog/tutorial-add-an-iframe-application-to-your-facebook-fan-page-fall-2012/</a></div>
<img src="http://feeds.feedburner.com/~r/etech-blog/~4/fOkLaRXhFWY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.excellencemagentoblog.com/magento-facebook-integration-facebook-page-and-apps/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://www.excellencemagentoblog.com/magento-facebook-integration-facebook-page-and-apps?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=magento-facebook-integration-facebook-page-and-apps</feedburner:origLink></item>
	</channel>
</rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

 Served from: www.excellencemagentoblog.com @ 2013-05-21 14:56:55 by W3 Total Cache -->
