SlideShare a Scribd company logo
How to Create Module to Track Affiliate Conversions?
Do you or the affiliate marketer know which conversions have been made by you, and which
conversions are made through the affiliate referrals? Do you inform your affiliate whenever a
conversion is made through their referral? Instead of keeping track manually, Magento allows you
to create a module that will track affiliate referrals and notify whenever the referral is converted.
The Pre-requisites
By now you must be aware with the basics of Magento and coding. You must have familiarized
yourself with creating Magento modules.
Whenever you are making certain website specific settings, you would add them as configurable
options in the admin panel. That’s why the module you are coding for affiliate conversions will
become a community module and will be stored in the following path app/code/community. When
you create a community module or code, you are actually allowing future use of the module, as it is,
without any modifications.
To create a module to track affiliate conversions, you will need to create empty file structures
containing empty files
Here’s a code that will help you create this structure
app
- code
- community
- Affiliate
- Block
- Conversion.php
- Model
- Observer.php
- etc
- config.xml
- design
- frontend
- base
- default
- layout
- Example_affiliate.xml
- template
- Example_affiliate
- conversion.phtml
- etc
- modules
- Example_Affiliate.xml
To add content for the example module, here is the code
<&quest;xml version="1.0" encoding="UTF-8"&quest;>
<config>
<modules>
<Example_Affiliate>
<active>true</active>
<codePool>community</codePool>
</Example_Affiliate>
</modules>
</config>
Steps to Track the Affiliate Referral
When you set out to track affiliates, the first thing you track is the content that referred your
website. Was it a website, a newsletter, or similar kind of content that included your website
details? You will also need to know the affiliate ID to reward the affiliate once the conversion has
been made
Example.com/&quest;utm_source=some_affiliate_id
The Event Observer
$_GET parameter is used to fetch a particular URL and use it for affiliate marketing. It is necessary
for you, as a store to include this parameter throughout your website, so that affiliates can link the
page containing the product/service of interest to their readers or users.
You should not bring any changes to the core. That’s why it is necessary to use event_observer that
will connect with the pages and fetch the required data
The single event that will be dispatched across the different parts of the website would be
controller_front_init_before
Let’s create a config.xml along with an observer for this particular event
<&quest;xml version="1.0" encoding="UTF-8"&quest;>
<config>
<modules>
<Example_Affiliate>
<version>0.0.1</version>
</Example_Affiliate>
</modules>
<global>
<models>
<Example_affiliate>
<class>Example_Affiliate_Model</class>
</Example_affiliate>
</models>
<events>
<controller_front_init_before>
<observers>
<Example_affiliate>
<class>Example_affiliate/observer</class>
<method>captureReferral</method>
<type>singleton</type>
</Example_affiliate >
</observers>
</controller_front_init_before>
</events>
</global>
</config>
To capture the referral the following function will be called
Example_Affiliate_Model_Observer::captureReferral()
It is important to add content to observer.php that you have just created so that the referral can
fetch some data
<&quest;php
class Example_Affiliate_Model_Observer
{
public function captureReferral(Varien_Event_Observer $observer)
{
// here we add the logic to capture the referring affiliate ID
}
}
Capturing and Saving Affiliate ID
To capture the affiliate ID, the event observer that you just created controller_front_init_before will
be sent out from the Magento core defined by Mage_Core_Controller_Varien_Front::init() along with
a reference specified for the same class as defined in the event dispatched from
app/code/core/Mage/Core/Controller/Varien/Front.php. The code snippet used to dispatch the
event is
Mage::dispatchEvent(
'controller_front_init_before',
array('front' => $this)
);
If you want to gain access to the core file defined by Mage_Core_Controller_Varien_Front you will
need to paste the code given below to your event_observer module
<&quest;php
class Example_Affiliate_Model_Observer
{
public function captureReferral(Varien_Event_Observer $observer)
{
$frontController = $observer->getEvent()->getFront();
}
}
This controller checks and analyzes the different URLs that are passed through it. Through this, you
are able to access the object. Now, you need to check for $_GET parameter within this object. The
following code will help you perform the necessary action
<&quest;php
class Example_Affiliate_Model_Observer
{
public function captureReferral(Varien_Event_Observer $observer)
{
$frontController = $observer->getEvent()->getFront();
$utmSource = $frontController->getRequest()
->getParam('utm_source', false);
if ($utmSource) {
// here we will save the referrer affiliate ID
}
}
}
Here the getRequest() is used to regain the contents of Mage_Core_Controller_Request_Http
instance present within the controller. This instance will possess all the requisite details related to
the URL including the $_Post and $_Get parameters. Using the getParam() method, you can easily
retrieve the required details. $utmsource will contain the affiliate ID referring the link
Now, you know the affiliate ID. You will need to save the details so that you can reward the affiliate
in case the user who has clicked the link gets converted.
As you are aware, Magento has a core functionality of dealing with Cookies. You can easily use
$_COOKIE to save the $utmsource for the affiliate
<&quest;php
class Example_Affiliate_Model_Observer
{
const COOKIE_KEY_SOURCE = 'Example_affiliate_source';
public function captureReferral(Varien_Event_Observer $observer)
{
$frontController = $observer->getEvent()->getFront();
$utmSource = $frontController->getRequest()
->getParam('utm_source', false);
if ($utmSource) {
Mage::getModel('core/cookie')->set(
self::COOKIE_KEY_SOURCE,
$utmSource,
$this->_getCookieLifetime()
);
}
}
protected function _getCookieLifetime()
{
$days = 30;
// convert to seconds
return (int)86400 * $days;
}
}
Constants are truly useful when you need to use the same value across locations. In this code
constant COOKIE_KEY_SOURCE has been defined. With a constant, you don’t need to keep changing
the code with change in values. The code _getcookielifetime() has been defined to retrieve the
cookie for a lifetime. You can always define your lifetime. In this case, the number of days has been
set to 30 days.
Notifying the Affiliate on Conversion
The above processes have allowed us to include the affiliate ID in the cookie. Let’s say the customer
who has been referenced to your website has successfully checked out fromyour website. Now, you
need to notify the affiliate about the conversion, and reward them.
You can create event_observer and notify using the server side API. In this case, Magento layout and
introduce the necessary HTML code at the bottom of the page declaring order success
In order to perform this, you will need to update config.xml to introduce the different blocks and
layout created for this purpose
<&quest;xml version="1.0" encoding="UTF-8"&quest;>
<config>
<modules>
<Example_Affiliate>
<version>0.0.1</version>
</Example_Affiliate>
</modules>
<global>
<blocks>
<Example_affiliate>
<class>Example_Affiliate_Block</class>
</Example_affiliate>
</blocks>
<models>
<Example_affiliate>
<class>Example_Affiliate_Model</class>
</Example_affiliate>
</models>
<events>
<controller_front_init_before>
<observers>
<Example_affiliate>
<class>Example_affiliate/observer</class>
<method>captureReferral</method>
<type>singleton</type>
</Example_affiliate >
</observers>
</controller_front_init_before>
</events>
</global>
<frontend>
<layout>
<updates>
<Example_affiliate
module="Example_Affiliate">
<file>Example_affiliate.xml</file>
</Example_affiliate>
</updates>
</layout>
</frontend>
</config>
Adding New Layout with Template Files and Custom Blocks
You will need to modify the layout handle onepage_checkout_success. For this you will need to
update the layout file Example_affiliate.xml
<&quest;xml version="1.0" encoding="UTF-8"&quest;>
<layout>
<checkout_onepage_success>
<reference name="before_body_end">
<block type="Example_affiliate/conversion"
name="Example_affiliate_conversion"
template="Example_affiliate/conversion.phtml" />
</reference>
</checkout_onepage_success>
</layout>
Using the below code you can define a new template file. Contents for conversion.phtml will be
affiliate specific. For the sake of simplicity, the code being considered here is generic
<img
src="http://media.Example.com/themes/Examplev4/images/logo.png
&quest;merchant_id=<&quest;php echo $this->getMerchantId() &quest;>
&affiliate_id=<&quest;php echo $this->getAffiliateId() &quest;>"
width="1"
height="1"
/>
Now, you need to create a custom block to enter the data
<&quest;php
class Example_Affiliate_Block_Conversion
extends Mage_Core_Block_Template
{
public function getMerchantId()
{
return '12345';
}
public function getAffiliateId()
{
return Mage::getModel('core/cookie')->get(
Example_Affiliate_Model_Observer::COOKIE_KEY_SOURCE
);
}
}
Next go to System>Configuration and start configuring the different elements that would be needed
for each Magento instance
Configuring a New System Configuration Tab
For the purpose of notification, you will create a new system configuration tab.
app/code/community/Example/Affiliate/etc/system.xml
Paste the following code in this path
<&quest;xml version="1.0" encoding="UTF-8"&quest;>
<config>
<!-- we are defining a new tab -->
<tabs>
<!-- our tab unique short name -->
<Example>
<!-- the title of our tab in the admin panel sidebar -->
<label>Example Magazine</label>
<!-- the order our tab should appear on the sidebar -->
<sort_order>100</sort_order>
</Example>
</tabs>
</config>
Now, create a new file app/code/community/Example/Affiliate/etc/adminhtml.xml to configure
ACL settings
<&quest;xml version="1.0" encoding="UTF-8"&quest;>
<adminhtml>
<acl>
<resources>
<admin>
<children>
<system>
<children>
<config>
<children>
<Example_affiliate>
<title>Example Magazine
Affiliate</title>
</Example_affiliate>
</children>
</config>
</children>
</system>
</children>
</admin>
</resources>
</acl>
</adminhtml>
Add the items required for new system configuration
<&quest;xml version="1.0" encoding="UTF-8"&quest;>
<config>
<tabs>
<Example>
<label>Example Magazine</label>
<sort_order>100</sort_order>
</Example>
</tabs>
<!-- we are adding a new section to our tab -->
<sections>
<!-- unique shortname for our section -->
<Example_affiliate>
<!-- the title of our section in the sidebar -->
<label>Affiliate Tracking</label>
<!-- the tab under which we want our section to appear -->
<tab>Example</tab>
<!-- order of section relative to our tab -->
<sort_order>10</sort_order>
<!-- visibility of our section -->
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<!-- we are adding some new groups to our section -->
<groups>
<!-- the unique short code for our group -->
<general>
<!-- the title of our group -->
<label>General Settings</label>
<!-- order of group relative to the section -->
<sort_order>10</sort_order>
<!-- visibility of our group -->
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<!-- we are adding some new fields to our group -->
<fields>
<!-- the unique short code for our field -->
<status>
<!-- the label of our field -->
<label>Enabled</label>
<!-- the type of our field -->
<frontend_type>select</frontend_type>
<!-- the source of our 'select' type -->
<source_model>
adminhtml/system_config_source_enabledisable
</source_model>
<!-- order relative to the group -->
<sort_order>10</sort_order>
<!-- visibility of our field -->
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</status>
<merchant_id>
<label>Merchant ID</label>
<frontend_type>text</frontend_type>
<sort_order>20</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</merchant_id>
</fields>
</general>
<cookie>
<label>Cookie Settings</label>
<sort_order>20</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<timeout>
<label>Cookie Timeout</label>
<frontend_type>text</frontend_type>
<sort_order>10</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<!--
we can add a comment that
will appear below the field
-->
<comment><![CDATA[
This is the amount of time
an affiliate cookie will last, in days
]]></comment>
</timeout>
</fields>
</cookie>
</groups>
</Example_affiliate>
</sections>
</config>
Define the default admin settings using the following code
<&quest;xml version="1.0" encoding="UTF-8"&quest;>
<config>
<modules>
<Example_Affiliate>
<version>0.0.1</version>
</Example_Affiliate>
</modules>
<global>
<blocks>
<Example_affiliate>
<class>Example_Affiliate_Block</class>
</Example_affiliate>
</blocks>
<models>
<Example_affiliate>
<class>Example_Affiliate_Model</class>
</Example_affiliate>
</models>
<events>
<controller_front_init_before>
<observers>
<Example_affiliate>
<class>Example_affiliate/observer</class>
<method>captureReferral</method>
<type>singleton</type>
</Example_affiliate >
</observers>
</controller_front_init_before>
</events>
</global>
<frontend>
<layout>
<updates>
<Example_affiliate
module="Example_Affiliate">
<file>Example_affiliate.xml</file>
</Example_affiliate>
</updates>
</layout>
</frontend>
<!-- we are setting the default value -->
<default>
<!-- this is the section short name -->
<Example_affiliate>
<!-- this is the group short name -->
<cookie>
<!-- this is the field short name -->
<timeout>30</timeout>
</cookie>
</Example_affiliate>
</default>
</config>
Now, most of things required by your layout have been configured. Access the system configuration
values using the following snippet
<&quest;php $value = Mage::getStoreConfig('system/config/path'); &quest;>
Make sure you change the default system configuration path with the new one
You can now replace the hard coded cookie lifetime value with the admin panel system
configuration value
<&quest;php
class Example_Affiliate_Model_Observer
{
const COOKIE_KEY_SOURCE = 'Example_affiliate_source';
public function captureReferral(Varien_Event_Observer $observer)
{
$frontController = $observer->getEvent()->getFront();
$utmSource = $frontController->getRequest()
->getParam('utm_source', false);
if ($utmSource) {
Mage::getModel('core/cookie')->set(
self::COOKIE_KEY_SOURCE,
$utmSource,
$this->_getCookieLifetime()
);
}
}
protected function _getCookieLifetime()
{
$days = Mage::getStoreConfig(
'Example_affiliate/cookie/timeout'
);
// convert to seconds
return (int)86400 * $days;
}
}
It’s time to call the merchant ID of the affiliate to the layout defined
<&quest;php
class Example_Affiliate_Block_Conversion
extends Mage_Core_Block_Template
{
public function getIsActive()
{
return Mage::getStoreConfig(
'Example_affiliate/general/status'
) &quest; true : false;
}
public function getMerchantId()
{
return Mage::getStoreConfig(
'Example_affiliate/general/merchant_id'
);
}
public function getAffiliateId()
{
return Mage::getModel('core/cookie')->get(
Example_Affiliate_Model_Observer::COOKIE_KEY_SOURCE
);
}
}
You can easily enable or disable this new configuration system tab conversion.phtml with this code.
This way it will be called only when the checkout has been a success
<&quest;php if ($this->getIsActive()): &quest;>
<img
src="http://media.Example.com/themes/Examplev4/images/logo.png
&quest;merchant_id=<&quest;php echo $this->getMerchantId() &quest;>
&affiliate_id=<&quest;php echo $this->getAffiliateId() &quest;>"
width="1"
height="1"
/>
<&quest;php endif; &quest;>
Conclusion
It is important to create and structure community modules in the admin panel so that you can
easily use it across websites. To customize, you just need to fine tune the code to suit requirements.
Note: Don’t forget to take a backup of your system configuration and other existing files before you
create the module using this code
Original Source:
https://medium.com/@semaphoresoftware/how-to-create-module-to-track-affiliate-conversions-
20749a696ced

More Related Content

PDF
Manipulating Magento - Meet Magento Belgium 2017
PDF
Introduction to Magento 2 module development - PHP Antwerp Meetup 2017
PDF
Leverage StandardSetController in Apex and Visualforce
PDF
Difference between-action-support
PDF
Manipulating Magento - Mage Titans Italy 2018
PDF
Visualforce: Using ActionFunction vs. RemoteAction
PDF
The EffiChange XPager Suite: Understanding XPages Scaffolding
PPT
Visualforce: Using JavaScript Remoting for Apex Controllers
Manipulating Magento - Meet Magento Belgium 2017
Introduction to Magento 2 module development - PHP Antwerp Meetup 2017
Leverage StandardSetController in Apex and Visualforce
Difference between-action-support
Manipulating Magento - Mage Titans Italy 2018
Visualforce: Using ActionFunction vs. RemoteAction
The EffiChange XPager Suite: Understanding XPages Scaffolding
Visualforce: Using JavaScript Remoting for Apex Controllers

What's hot (9)

PDF
Rails Plugins - Linux For You, March 2011 Issue
PPTX
Subscribed zuora forsalesforce training -section301-final
PDF
[2019] 벅스 5.0 (feat. Kotlin, Jetpack)
PDF
[2019] 스몰 스텝: Android 렛츠기릿!
PPTX
Hands on SPA development
PDF
實戰Facebook Marketing API
DOCX
Layout
PDF
Facebook广告API 101
KEY
Presenters in Rails
Rails Plugins - Linux For You, March 2011 Issue
Subscribed zuora forsalesforce training -section301-final
[2019] 벅스 5.0 (feat. Kotlin, Jetpack)
[2019] 스몰 스텝: Android 렛츠기릿!
Hands on SPA development
實戰Facebook Marketing API
Layout
Facebook广告API 101
Presenters in Rails
Ad

Viewers also liked (9)

PDF
Flyer CNAM VAE
DOCX
Testimonial from Ronnie Verhelst
PDF
O Manual Para Turnês Independentes
PDF
JURNAL ANAK
PDF
Thermomix Brochure TM5
PDF
Nikolay Markov Nikolov: The way to go – acting students, directing teachers, ...
PPTX
Does Your Festival or Event Make Cent$
PDF
Brussels document en_presentation
PDF
Construir la Integración Regional desde la Cooperación Comercial y el Comerci...
 
Flyer CNAM VAE
Testimonial from Ronnie Verhelst
O Manual Para Turnês Independentes
JURNAL ANAK
Thermomix Brochure TM5
Nikolay Markov Nikolov: The way to go – acting students, directing teachers, ...
Does Your Festival or Event Make Cent$
Brussels document en_presentation
Construir la Integración Regional desde la Cooperación Comercial y el Comerci...
 
Ad

Similar to How to Create Module to Track Affiliate Conversions? (20)

PDF
PrestaShop Affiliates and Referrals EN Guide
PPTX
Magento 2 Affiliate System
PDF
Affiliated.pdf
PPTX
Magento eConnect for Infor M3
PDF
Magento features list
PDF
Affiliate Management Platform
PPTX
Actionable Steps to Boost Your Affiliate Program in 2015
PDF
Magento community edition user guide
PDF
Enhanced ecommerce tracking
PPTX
The Performance Marketing Primer
PDF
Magento Affiliate extension
PDF
Building an E-Commerce Business with Shopify
PDF
PPTX
Magento's Imagine eCommerce Conference 2011 - Mash-up of Magento and Salesfor...
PDF
Rg guide
PDF
Affiliate Marketing E-Guide.
PDF
PPTX
PDF
Magento feature list
PDF
Magento feature-list
PrestaShop Affiliates and Referrals EN Guide
Magento 2 Affiliate System
Affiliated.pdf
Magento eConnect for Infor M3
Magento features list
Affiliate Management Platform
Actionable Steps to Boost Your Affiliate Program in 2015
Magento community edition user guide
Enhanced ecommerce tracking
The Performance Marketing Primer
Magento Affiliate extension
Building an E-Commerce Business with Shopify
Magento's Imagine eCommerce Conference 2011 - Mash-up of Magento and Salesfor...
Rg guide
Affiliate Marketing E-Guide.
Magento feature list
Magento feature-list

Recently uploaded (20)

PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Cloud computing and distributed systems.
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
KodekX | Application Modernization Development
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
Understanding_Digital_Forensics_Presentation.pptx
Encapsulation theory and applications.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Network Security Unit 5.pdf for BCA BBA.
20250228 LYD VKU AI Blended-Learning.pptx
Big Data Technologies - Introduction.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Cloud computing and distributed systems.
The AUB Centre for AI in Media Proposal.docx
MYSQL Presentation for SQL database connectivity
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
MIND Revenue Release Quarter 2 2025 Press Release
Mobile App Security Testing_ A Comprehensive Guide.pdf
KodekX | Application Modernization Development
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Chapter 3 Spatial Domain Image Processing.pdf
NewMind AI Weekly Chronicles - August'25 Week I

How to Create Module to Track Affiliate Conversions?

  • 1. How to Create Module to Track Affiliate Conversions? Do you or the affiliate marketer know which conversions have been made by you, and which conversions are made through the affiliate referrals? Do you inform your affiliate whenever a conversion is made through their referral? Instead of keeping track manually, Magento allows you to create a module that will track affiliate referrals and notify whenever the referral is converted. The Pre-requisites By now you must be aware with the basics of Magento and coding. You must have familiarized yourself with creating Magento modules. Whenever you are making certain website specific settings, you would add them as configurable options in the admin panel. That’s why the module you are coding for affiliate conversions will become a community module and will be stored in the following path app/code/community. When you create a community module or code, you are actually allowing future use of the module, as it is, without any modifications. To create a module to track affiliate conversions, you will need to create empty file structures containing empty files Here’s a code that will help you create this structure app - code - community - Affiliate - Block - Conversion.php - Model - Observer.php - etc
  • 2. - config.xml - design - frontend - base - default - layout - Example_affiliate.xml - template - Example_affiliate - conversion.phtml - etc - modules - Example_Affiliate.xml To add content for the example module, here is the code <&quest;xml version="1.0" encoding="UTF-8"&quest;> <config> <modules> <Example_Affiliate> <active>true</active> <codePool>community</codePool> </Example_Affiliate> </modules> </config> Steps to Track the Affiliate Referral When you set out to track affiliates, the first thing you track is the content that referred your website. Was it a website, a newsletter, or similar kind of content that included your website details? You will also need to know the affiliate ID to reward the affiliate once the conversion has been made Example.com/&quest;utm_source=some_affiliate_id The Event Observer $_GET parameter is used to fetch a particular URL and use it for affiliate marketing. It is necessary for you, as a store to include this parameter throughout your website, so that affiliates can link the page containing the product/service of interest to their readers or users. You should not bring any changes to the core. That’s why it is necessary to use event_observer that will connect with the pages and fetch the required data The single event that will be dispatched across the different parts of the website would be controller_front_init_before Let’s create a config.xml along with an observer for this particular event <&quest;xml version="1.0" encoding="UTF-8"&quest;> <config>
  • 3. <modules> <Example_Affiliate> <version>0.0.1</version> </Example_Affiliate> </modules> <global> <models> <Example_affiliate> <class>Example_Affiliate_Model</class> </Example_affiliate> </models> <events> <controller_front_init_before> <observers> <Example_affiliate> <class>Example_affiliate/observer</class> <method>captureReferral</method> <type>singleton</type> </Example_affiliate > </observers> </controller_front_init_before> </events> </global> </config> To capture the referral the following function will be called Example_Affiliate_Model_Observer::captureReferral() It is important to add content to observer.php that you have just created so that the referral can fetch some data <&quest;php class Example_Affiliate_Model_Observer { public function captureReferral(Varien_Event_Observer $observer) { // here we add the logic to capture the referring affiliate ID } } Capturing and Saving Affiliate ID To capture the affiliate ID, the event observer that you just created controller_front_init_before will be sent out from the Magento core defined by Mage_Core_Controller_Varien_Front::init() along with a reference specified for the same class as defined in the event dispatched from app/code/core/Mage/Core/Controller/Varien/Front.php. The code snippet used to dispatch the event is Mage::dispatchEvent( 'controller_front_init_before',
  • 4. array('front' => $this) ); If you want to gain access to the core file defined by Mage_Core_Controller_Varien_Front you will need to paste the code given below to your event_observer module <&quest;php class Example_Affiliate_Model_Observer { public function captureReferral(Varien_Event_Observer $observer) { $frontController = $observer->getEvent()->getFront(); } } This controller checks and analyzes the different URLs that are passed through it. Through this, you are able to access the object. Now, you need to check for $_GET parameter within this object. The following code will help you perform the necessary action <&quest;php class Example_Affiliate_Model_Observer { public function captureReferral(Varien_Event_Observer $observer) { $frontController = $observer->getEvent()->getFront(); $utmSource = $frontController->getRequest() ->getParam('utm_source', false); if ($utmSource) { // here we will save the referrer affiliate ID } } } Here the getRequest() is used to regain the contents of Mage_Core_Controller_Request_Http instance present within the controller. This instance will possess all the requisite details related to the URL including the $_Post and $_Get parameters. Using the getParam() method, you can easily retrieve the required details. $utmsource will contain the affiliate ID referring the link Now, you know the affiliate ID. You will need to save the details so that you can reward the affiliate in case the user who has clicked the link gets converted. As you are aware, Magento has a core functionality of dealing with Cookies. You can easily use $_COOKIE to save the $utmsource for the affiliate <&quest;php class Example_Affiliate_Model_Observer { const COOKIE_KEY_SOURCE = 'Example_affiliate_source';
  • 5. public function captureReferral(Varien_Event_Observer $observer) { $frontController = $observer->getEvent()->getFront(); $utmSource = $frontController->getRequest() ->getParam('utm_source', false); if ($utmSource) { Mage::getModel('core/cookie')->set( self::COOKIE_KEY_SOURCE, $utmSource, $this->_getCookieLifetime() ); } } protected function _getCookieLifetime() { $days = 30; // convert to seconds return (int)86400 * $days; } } Constants are truly useful when you need to use the same value across locations. In this code constant COOKIE_KEY_SOURCE has been defined. With a constant, you don’t need to keep changing the code with change in values. The code _getcookielifetime() has been defined to retrieve the cookie for a lifetime. You can always define your lifetime. In this case, the number of days has been set to 30 days. Notifying the Affiliate on Conversion The above processes have allowed us to include the affiliate ID in the cookie. Let’s say the customer who has been referenced to your website has successfully checked out fromyour website. Now, you need to notify the affiliate about the conversion, and reward them. You can create event_observer and notify using the server side API. In this case, Magento layout and introduce the necessary HTML code at the bottom of the page declaring order success In order to perform this, you will need to update config.xml to introduce the different blocks and layout created for this purpose <&quest;xml version="1.0" encoding="UTF-8"&quest;> <config> <modules> <Example_Affiliate> <version>0.0.1</version> </Example_Affiliate> </modules> <global>
  • 6. <blocks> <Example_affiliate> <class>Example_Affiliate_Block</class> </Example_affiliate> </blocks> <models> <Example_affiliate> <class>Example_Affiliate_Model</class> </Example_affiliate> </models> <events> <controller_front_init_before> <observers> <Example_affiliate> <class>Example_affiliate/observer</class> <method>captureReferral</method> <type>singleton</type> </Example_affiliate > </observers> </controller_front_init_before> </events> </global> <frontend> <layout> <updates> <Example_affiliate module="Example_Affiliate"> <file>Example_affiliate.xml</file> </Example_affiliate> </updates> </layout> </frontend> </config> Adding New Layout with Template Files and Custom Blocks You will need to modify the layout handle onepage_checkout_success. For this you will need to update the layout file Example_affiliate.xml <&quest;xml version="1.0" encoding="UTF-8"&quest;> <layout> <checkout_onepage_success> <reference name="before_body_end"> <block type="Example_affiliate/conversion" name="Example_affiliate_conversion" template="Example_affiliate/conversion.phtml" /> </reference> </checkout_onepage_success> </layout>
  • 7. Using the below code you can define a new template file. Contents for conversion.phtml will be affiliate specific. For the sake of simplicity, the code being considered here is generic <img src="http://media.Example.com/themes/Examplev4/images/logo.png &quest;merchant_id=<&quest;php echo $this->getMerchantId() &quest;> &affiliate_id=<&quest;php echo $this->getAffiliateId() &quest;>" width="1" height="1" /> Now, you need to create a custom block to enter the data <&quest;php class Example_Affiliate_Block_Conversion extends Mage_Core_Block_Template { public function getMerchantId() { return '12345'; } public function getAffiliateId() { return Mage::getModel('core/cookie')->get( Example_Affiliate_Model_Observer::COOKIE_KEY_SOURCE ); } } Next go to System>Configuration and start configuring the different elements that would be needed for each Magento instance Configuring a New System Configuration Tab For the purpose of notification, you will create a new system configuration tab. app/code/community/Example/Affiliate/etc/system.xml Paste the following code in this path <&quest;xml version="1.0" encoding="UTF-8"&quest;> <config> <!-- we are defining a new tab --> <tabs> <!-- our tab unique short name --> <Example> <!-- the title of our tab in the admin panel sidebar --> <label>Example Magazine</label> <!-- the order our tab should appear on the sidebar --> <sort_order>100</sort_order>
  • 8. </Example> </tabs> </config> Now, create a new file app/code/community/Example/Affiliate/etc/adminhtml.xml to configure ACL settings <&quest;xml version="1.0" encoding="UTF-8"&quest;> <adminhtml> <acl> <resources> <admin> <children> <system> <children> <config> <children> <Example_affiliate> <title>Example Magazine Affiliate</title> </Example_affiliate> </children> </config> </children> </system> </children> </admin> </resources> </acl> </adminhtml> Add the items required for new system configuration <&quest;xml version="1.0" encoding="UTF-8"&quest;> <config> <tabs> <Example> <label>Example Magazine</label> <sort_order>100</sort_order> </Example> </tabs> <!-- we are adding a new section to our tab --> <sections> <!-- unique shortname for our section --> <Example_affiliate> <!-- the title of our section in the sidebar --> <label>Affiliate Tracking</label> <!-- the tab under which we want our section to appear --> <tab>Example</tab>
  • 9. <!-- order of section relative to our tab --> <sort_order>10</sort_order> <!-- visibility of our section --> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <!-- we are adding some new groups to our section --> <groups> <!-- the unique short code for our group --> <general> <!-- the title of our group --> <label>General Settings</label> <!-- order of group relative to the section --> <sort_order>10</sort_order> <!-- visibility of our group --> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <!-- we are adding some new fields to our group --> <fields> <!-- the unique short code for our field --> <status> <!-- the label of our field --> <label>Enabled</label> <!-- the type of our field --> <frontend_type>select</frontend_type> <!-- the source of our 'select' type --> <source_model> adminhtml/system_config_source_enabledisable </source_model> <!-- order relative to the group --> <sort_order>10</sort_order> <!-- visibility of our field --> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>0</show_in_store> </status> <merchant_id> <label>Merchant ID</label> <frontend_type>text</frontend_type> <sort_order>20</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </merchant_id> </fields> </general>
  • 10. <cookie> <label>Cookie Settings</label> <sort_order>20</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <fields> <timeout> <label>Cookie Timeout</label> <frontend_type>text</frontend_type> <sort_order>10</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <!-- we can add a comment that will appear below the field --> <comment><![CDATA[ This is the amount of time an affiliate cookie will last, in days ]]></comment> </timeout> </fields> </cookie> </groups> </Example_affiliate> </sections> </config> Define the default admin settings using the following code <&quest;xml version="1.0" encoding="UTF-8"&quest;> <config> <modules> <Example_Affiliate> <version>0.0.1</version> </Example_Affiliate> </modules> <global> <blocks> <Example_affiliate> <class>Example_Affiliate_Block</class> </Example_affiliate> </blocks> <models> <Example_affiliate> <class>Example_Affiliate_Model</class> </Example_affiliate>
  • 11. </models> <events> <controller_front_init_before> <observers> <Example_affiliate> <class>Example_affiliate/observer</class> <method>captureReferral</method> <type>singleton</type> </Example_affiliate > </observers> </controller_front_init_before> </events> </global> <frontend> <layout> <updates> <Example_affiliate module="Example_Affiliate"> <file>Example_affiliate.xml</file> </Example_affiliate> </updates> </layout> </frontend> <!-- we are setting the default value --> <default> <!-- this is the section short name --> <Example_affiliate> <!-- this is the group short name --> <cookie> <!-- this is the field short name --> <timeout>30</timeout> </cookie> </Example_affiliate> </default> </config> Now, most of things required by your layout have been configured. Access the system configuration values using the following snippet <&quest;php $value = Mage::getStoreConfig('system/config/path'); &quest;> Make sure you change the default system configuration path with the new one
  • 12. You can now replace the hard coded cookie lifetime value with the admin panel system configuration value <&quest;php class Example_Affiliate_Model_Observer { const COOKIE_KEY_SOURCE = 'Example_affiliate_source'; public function captureReferral(Varien_Event_Observer $observer) { $frontController = $observer->getEvent()->getFront(); $utmSource = $frontController->getRequest() ->getParam('utm_source', false); if ($utmSource) { Mage::getModel('core/cookie')->set( self::COOKIE_KEY_SOURCE, $utmSource, $this->_getCookieLifetime() ); } } protected function _getCookieLifetime() { $days = Mage::getStoreConfig( 'Example_affiliate/cookie/timeout' ); // convert to seconds return (int)86400 * $days; } } It’s time to call the merchant ID of the affiliate to the layout defined <&quest;php class Example_Affiliate_Block_Conversion extends Mage_Core_Block_Template { public function getIsActive() { return Mage::getStoreConfig( 'Example_affiliate/general/status' ) &quest; true : false; } public function getMerchantId() { return Mage::getStoreConfig(
  • 13. 'Example_affiliate/general/merchant_id' ); } public function getAffiliateId() { return Mage::getModel('core/cookie')->get( Example_Affiliate_Model_Observer::COOKIE_KEY_SOURCE ); } } You can easily enable or disable this new configuration system tab conversion.phtml with this code. This way it will be called only when the checkout has been a success <&quest;php if ($this->getIsActive()): &quest;> <img src="http://media.Example.com/themes/Examplev4/images/logo.png &quest;merchant_id=<&quest;php echo $this->getMerchantId() &quest;> &affiliate_id=<&quest;php echo $this->getAffiliateId() &quest;>" width="1" height="1" /> <&quest;php endif; &quest;> Conclusion It is important to create and structure community modules in the admin panel so that you can easily use it across websites. To customize, you just need to fine tune the code to suit requirements. Note: Don’t forget to take a backup of your system configuration and other existing files before you create the module using this code Original Source: https://medium.com/@semaphoresoftware/how-to-create-module-to-track-affiliate-conversions- 20749a696ced