我正在使用magento中的Instagram API。如果他们在Instagram上关注我们的商店,我会为instagram的关注者提供优惠券。
我正在使用curl使用PHP对instagram进行API调用。目前,我将API调用包装在自定义模块中的辅助函数中。我是否应该将这些调用包装在模型中的函数中?
例如。我正在对Instagram进行API调用,以确定当前用户是否关注我的帐户。因此,在控制器中,我正在调用助手函数,该函数将关注状态返回给控制器。然后在我的控制器中,如有必要,我将更新我的模型。
将这些API调用放入辅助函数中,对吗?什么时候使用助手而不是模型?
<?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
);
}
}