Files
nextcloud-analytics/oauth-helper.php
2026-02-16 17:18:31 +00:00

91 lines
2.7 KiB
PHP

<?php
/**
* OAuth 2.0 Helper for Google Analytics
*
* Usage:
* 1. Get authorization code from OAuth flow (see guide)
* 2. Run: php oauth-helper.php YOUR_AUTHORIZATION_CODE
* 3. Get refresh_token output
* 4. Enter refresh_token into Nextcloud plugin settings
*/
// Configuration - Update with your values
$CLIENT_ID = 'YOUR_CLIENT_ID.apps.googleusercontent.com';
$CLIENT_SECRET = 'GOCSPX-XXXXXXXXXXXXXX'; // From Google Cloud Console
$REDIRECT_URI = 'https://teamworkapps.com/index.php/apps/analyticshub/';
// Get authorization code from command line
if ($argc < 2) {
echo "Usage: php oauth-helper.php <authorization_code>\n";
echo "\n";
echo "Get authorization code from:\n";
echo "https://accounts.google.com/o/oauth2/v2/auth?\n";
echo " client_id=$CLIENT_ID\n";
echo " &redirect_uri=" . urlencode($REDIRECT_URI) . "\n";
echo " &response_type=code\n";
echo " &scope=" . urlencode('https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/analytics') . "\n";
echo "\n";
echo "After granting permissions, copy the 'code' parameter from the redirect URL.\n";
echo "\n";
die(1);
}
$authCode = $argv[1];
// Exchange authorization code for tokens
$tokenUrl = 'https://oauth2.googleapis.com/token';
$postData = [
'code' => $authCode,
'client_id' => $CLIENT_ID,
'client_secret' => $CLIENT_SECRET,
'redirect_uri' => $REDIRECT_URI,
'grant_type' => 'authorization_code'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Curl error: " . curl_error($ch) . "\n";
curl_close($ch);
die(1);
}
curl_close($ch);
if ($httpCode !== 200) {
echo "Error: HTTP $httpCode\n";
echo "Response: $response\n";
die(1);
}
// Parse JSON response
$data = json_decode($response, true);
if (!$data || empty($data['refresh_token'])) {
echo "Error: No refresh_token in response\n";
echo "Response: " . json_encode($data, JSON_PRETTY_PRINT) . "\n";
die(1);
}
// Success!
echo "✅ Success! Here are your tokens:\n\n";
echo "ACCESS TOKEN (expires in 1 hour):\n";
echo $data['access_token'] . "\n\n";
echo "REFRESH TOKEN (save this in Nextcloud plugin):\n";
echo $data['refresh_token'] . "\n\n";
echo "Token type: " . $data['token_type'] . "\n";
echo "Expires in: " . $data['expires_in'] . " seconds\n";
echo "\n";
echo "💡 Now enter the REFRESH TOKEN into the plugin settings!\n";