I am working with the Instagram API in magento. I am giving coupons to my instagram followers if they follow our store on Instagram.
I am making the API calls to instagram in PHP using curl. Currently I am wrapping the API calls in helper functions inside my custom module. Should I instead be wrapping these calls in a function inside a model?
For example. I am making an API call to Instagram to determine if the current user is following my account. So, in my controller, I am making a call to my helper function which returns the follow status to my controller. In my controller, I will then update my models if necessary.
Am I correct in putting these API calls inside helper functions? When do I use helpers as opposed to models?
<?php
class Company_SocialCoupons_InstagramController extends Mage_Core_Controller_Front_Action
{
public function followAction() {
$status = Mage::helper('socialcoupons/instagram')->getFollow();
if ($status == 'follows') {
// 1. ADD DATA TO MY DATABASE using my custom model
// - Ex. Mage::getModel('socialcoupons/instagram')->setInstagramId(*IGID*), etc.
// 2. CREATE COUPON
// 3. EMAIL COUPON TO CUSTOMER
}
}
class Company_SocialCoupons_Helper_Instagram extends Mage_Core_Helper_Abstract
{
public function getfollow() {
$accessToken = $this->getAccessToken();
$relationshipsUrl = 'https://api.instagram.com/v1/users/' . $this->getUserId() . '/relationship?access_token=' . $accessToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $relationshipsUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonData = curl_exec($ch);
curl_close($ch);
$response = json_decode($jsonData, true);
$status = $response['data']['outgoing_status'];
return $status;
}
public function generateAccessToken($code) {
// exchange code for access token
$accessTokenUrl = 'https://api.instagram.com/oauth/access_token';
$data = array(
'client_id' => $this->getClientId(),
'client_secret' => $this->getClientSecret(),
'code' => $code,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->getRedirectUri()
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $accessTokenUrl);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonData = curl_exec($ch);
curl_close($ch);
$response = json_decode($jsonData, true);
if (isset($response['error_type'])) { // no error
Mage::getSingleton('core/session')->unsInstagramAccessToken();
Mage::getSingleton('core/session')->addError($response['error_message']);
return $this->_redirect('*/*/authorize');
}
$accessToken = $response['access_token'];
$id = $response['user']['id'];
$username = $response['user']['username'];
Mage::getSingleton('core/session')->setInstagramAccessToken($accessToken);
return array(
'id' => $id,
'username' => $username
);
}
}