'.$this->l('Google is unreachable (check your firewall)').'
' : '').'
'.($online ? '' : '
'.$this->l('You are currently testing your shop on a local server. In order to enjoy the full features, you need to put your shop on an online server.').'
').'
');
}
$html .= '
'.$this->l('Please be aware the Google Analytics API module will only work if you either:').'
'.$this->l('have installed and configured the “Google Analytics” module').'
'.$this->l('or have already embedded the Google Analytics script into your shop.').'
';
if (Tools::getValue('PS_GAPI_VERSION'))
Configuration::updateValue('PS_GAPI_VERSION', (int)Tools::getValue('PS_GAPI_VERSION'));
$helper = new HelperOptions($this);
$helper->id = $this->id;
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->module = $this;
$fields_options = array(
'general' => array(
'title' => $this->l('Which Google Analytics API version do you want to use?'),
'fields' => $fields = array(
'PS_GAPI_VERSION' => array(
'type' => 'radio',
'choices' => array(
13 => $this->l('v1.3: easy to configure but deprecated and less secure'),
30 => $this->l('v3.0 with OAuth 2.0: most powerful and up-to-date version')
),
'visibility' => Shop::CONTEXT_SHOP
)
),
'submit' => array('title' => $this->l('Save and configure')),
)
);
$helper->tpl_vars = array('currentIndex' => $helper->currentIndex);
$html .= $helper->generateOptions($fields_options);
if (Configuration::get('PS_GAPI_VERSION') == 30)
$html .= $this->api_3_0_getContent();
elseif (Configuration::get('PS_GAPI_VERSION') == 13)
$html .= $this->api_1_3_getContent();
return $html;
}
public function requestReportData($dimensions, $metrics, $date_from = null, $date_to = null, $sort = null, $filters = null, $start = 1, $limit = 30)
{
if (Configuration::get('PS_GAPI_VERSION') == 30)
return $this->api_3_0_requestReportData($dimensions, $metrics, $date_from, $date_to, $sort, $filters, $start, $limit);
elseif (Configuration::get('PS_GAPI_VERSION') == 13)
return $this->api_1_3_requestReportData($dimensions, $metrics, $date_from, $date_to, $sort, $filters, $start, $limit);
}
public function api_3_0_authenticate()
{
$shop = new Shop(Shop::getContextShopID());
// https://developers.google.com/accounts/docs/OAuth2WebServer
$params = array(
'response_type' => 'code',
'client_id' => Configuration::get('PS_GAPI30_CLIENT_ID_TMP'),
'scope' => 'https://www.googleapis.com/auth/analytics.readonly',
'redirect_uri' => $shop->getBaseURL(true).'modules/'.$this->name.'/oauth2callback.php',
'state' => $this->context->employee->id.'-'.Tools::encrypt($this->context->employee->id.Configuration::get('PS_GAPI30_CLIENT_ID_TMP')),
'approval_prompt' => 'force',
'access_type' => 'offline'
);
Tools::redirectLink('https://accounts.google.com/o/oauth2/auth?'.http_build_query($params));
}
public function api_3_0_refreshtoken()
{
$params = array(
'client_id' => Configuration::get('PS_GAPI30_CLIENT_ID'),
'client_secret' => Configuration::get('PS_GAPI30_CLIENT_SECRET')
);
// https://developers.google.com/accounts/docs/OAuth2WebServer#offline
if (Configuration::get('PS_GAPI30_REFRESH_TOKEN'))
{
$params['grant_type'] = 'refresh_token';
$params['refresh_token'] = Configuration::get('PS_GAPI30_REFRESH_TOKEN');
}
else
{
$shop = new Shop(Shop::getContextShopID());
$params['grant_type'] = 'authorization_code';
$params['code'] = Configuration::get('PS_GAPI30_AUTHORIZATION_CODE');
$params['redirect_uri'] = $shop->getBaseURL(true).'modules/'.$this->name.'/oauth2callback.php';
}
$content = http_build_query($params);
$stream_context = stream_context_create(array(
'http' => array(
'method'=> 'POST',
'content' => $content,
'header' => "Content-type: application/x-www-form-urlencoded\r\nContent-length: ".strlen($content)."\r\n",
'timeout' => 5,
)
));
if (!$response_json = Tools::file_get_contents('https://accounts.google.com/o/oauth2/token', false, $stream_context))
return false;
$response = Tools::jsonDecode($response_json, true);
if (isset($response['error']))
return false;
Configuration::updateValue('PS_GAPI30_ACCESS_TOKEN', $response['access_token']);
Configuration::updateValue('PS_GAPI30_TOKEN_EXPIRATION', time() + (int)$response['expires_in']);
if (isset($response['refresh_token']))
Configuration::updateValue('PS_GAPI30_REFRESH_TOKEN', $response['refresh_token']);
return true;
}
public function api_3_0_isConfigured()
{
return (Configuration::get('PS_GAPI30_CLIENT_ID') && Configuration::get('PS_GAPI30_CLIENT_SECRET') && Configuration::get('PS_GAPI_PROFILE'));
}
public function api_3_0_getContent()
{
$html = '';
if (Tools::getValue('PS_GAPI30_CLIENT_ID'))
{
Configuration::updateValue('PS_GAPI30_REQUEST_URI_TMP', dirname($_SERVER['REQUEST_URI']).'/'.AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'));
Configuration::updateValue('PS_GAPI30_CLIENT_ID_TMP', trim(Tools::getValue('PS_GAPI30_CLIENT_ID')));
Configuration::updateValue('PS_GAPI30_CLIENT_SECRET_TMP', trim(Tools::getValue('PS_GAPI30_CLIENT_SECRET')));
Configuration::updateValue('PS_GAPI_PROFILE_TMP', trim(Tools::getValue('PS_GAPI_PROFILE')));
// This will redirect the user to Google API authentication page
$this->api_3_0_authenticate();
}
elseif (Tools::getValue('oauth2callback') == 'error')
$html .= $this->displayError('Google API: Access denied');
elseif (Tools::getValue('oauth2callback') == 'undefined')
$html .= $this->displayError('Something wrong happened with Google API authorization');
elseif (Tools::getValue('oauth2callback') == 'success')
{
if ($this->api_3_0_refreshtoken())
$html .= $this->displayConfirmation('Google API Authorization granted');
else
$html .= $this->displayError('Google API Authorization granted but access token cannot be retrieved');
}
$display_slider = true;
if ($this->api_3_0_isConfigured())
{
$result_test = $this->api_3_0_requestReportData('', 'ga:visits,ga:uniquePageviews', date('Y-m-d', strtotime('-1 day')), date('Y-m-d', strtotime('-1 day')), null, null, 1, 1);
if (!$result_test)
$html .= $this->displayError('Cannot retrieve test results');
else
{
$display_slider = false;
$html .= $this->displayConfirmation(sprintf($this->l('Yesterday, your store received the visit of %d people for a total of %d unique page views.'), $result_test[0]['metrics']['visits'], $result_test[0]['metrics']['uniquePageviews']));
}
}
if ($display_slider)
{
$shop = new Shop(Shop::getContextShopID());
$authorized_origin = $shop->domain;
$authorized_redirect = $shop->domain.$shop->getBaseURI().'modules/'.$this->name.'/oauth2callback.php';
$slides = array(
'Google API - 01 - Start.png' => $this->l('Go to https://code.google.com/apis/console and click the "Create Project" button'),
'Google API - 02 - Services.png' => $this->l('In the "APIS & AUTH > APIs" tab, switch on the Analytics API'),
'Google API - 03 - Terms.png' => $this->l('You may be asked to agree to the Terms of Service of Google APIs and Analytics API'),
'Google API - 04 - Services OK.png' => $this->l('You should now have something like that'),
'Google API - 05 - API Access.png' => $this->l('In the "APIS & AUTH > Credentials" tab, click the first, red, "Create new Client ID" button'),
'Google API - 06 - Create Client ID.png' =>
sprintf($this->l('Keep "Web application" selected and fill in the "Authorized Javascript Origins" area with "%s" and "%s" then the "Authorized Redirect URI" area with "%s" and "%s".'), 'http://'.$authorized_origin, 'https://'.$authorized_origin, 'http://'.$authorized_redirect, 'https://'.$authorized_redirect).'
'.$this->l('Then validate by clicking the "Create client ID" button'),
'Google API - 07 - API Access created.png' => $this->l('You should now have the following screen. Copy/Paste the "Client ID" and "Client secret" into the form below'),
'Google API - 08 - Profile ID.png' => $this->l('Now you need the ID of the Analytics Profile you want to connect. In order to find your Profile ID, connect to the Analytics dashboard, then look at the URL in the address bar. Your Profile ID is the number following a "p", as shown underlined in red on the screenshot')
);
$first_slide = key($slides);
$html .= '