'.$this->l('Google is unreachable').' ('.$this->l('check your firewall').')
' : '').'
'.($online ? '' : '
'.$this->l('Your store is not online').'
').'
');
}
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_ALL
)
),
'submit' => array('title' => $this->l('Save and configure')),
)
);
$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()
{
// 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' => Tools::getShopDomain(true, false).__PS_BASE_URI__.'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
{
$params['grant_type'] = 'authorization_code';
$params['code'] = Configuration::get('PS_GAPI30_AUTHORIZATION_CODE');
$params['redirect_uri'] = Tools::getShopDomain(true, false).__PS_BASE_URI__.'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)
{
$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 "Services" tab, switch on the Analytics API'),
'Google API - 03 - Terms.png' => $this->l('You will be asked to agree to the Terms of Service of Google APIs'),
'Google API - 04 - Terms.png' => $this->l('And the Terms of Service of Analytics API'),
'Google API - 05 - Services OK.png' => $this->l('You should now have something like that'),
'Google API - 06 - API Access.png' => $this->l('In the "API Access" tab, click the big, blue, "Create an OAuth 2.0 client ID..." button'),
'Google API - 07 - Create Client ID.png' => $this->l('Fill in the form with the name of your store, the URL of your logo and the URL of your store then click "Next"'),
'Google API - 08 - Create Client ID.png' => sprintf($this->l('Keep "Web application" select and fill in the "Authorized Redirect URIs" area with the following URL: %s (you may have to click the "more options" link). Then validate by clicking the "Create client ID" button'), Tools::getShopDomain(true, false).__PS_BASE_URI__.'modules/'.$this->name.'/oauth2callback.php'),
'Google API - 09 - 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 - 10 - Profile ID.png' => $this->l('Now you need the ID of the Analytics Profile you want to connect. In order to find you Profile ID, connect to the Analytics dashboard 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 .= '