Last active
April 26, 2020 11:43
-
-
Save nczz/99739ed652b988a2f8fc4754250692fd to your computer and use it in GitHub Desktop.
[PHP] 串接 AdSense Management API 取得網站廣告收益報表 https://www.mxp.tw/8930/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once '../vendor/autoload.php'; | |
define('TOKEN_FILENAME', '/PATH/TO/YOUR/TOKENFILE.dat', true); | |
$client = new Google_Client(); | |
$client->addScope('https://www.googleapis.com/auth/adsense.readonly'); | |
$client->setAccessType('offline'); | |
$client->setApprovalPrompt('force'); | |
$client->setAuthConfig('/PATH/TO/YOUR/client_secrets.json'); | |
$auth = ""; | |
$access_token = ""; | |
$refresh_token = ""; | |
$service = new Google_Service_AdSense($client); | |
function gapp_refresh_token($client, $auth) { | |
$params = array( | |
"client_id" => $client->getClientId(), | |
"client_secret" => $client->getClientSecret(), | |
"refresh_token" => $auth['refresh_token'], | |
"grant_type" => "refresh_token", | |
); | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token'); | |
curl_setopt($ch, CURLOPT_POST, true); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $params); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); | |
$r = curl_exec($ch); | |
curl_close($ch); | |
$g_res = json_decode($r, true); | |
$access_token = $g_res['access_token']; | |
$expires_in = $g_res['expires_in']; | |
$scope = $g_res['scope']; | |
$auth['access_token']['access_token'] = $access_token; | |
$auth['access_token']['created'] = time(); | |
$auth['expires_time'] = intval($expires_in) + time() - 30; | |
file_put_contents(TOKEN_FILENAME, json_encode($auth)); | |
$client->setAccessToken($auth['access_token']); | |
return $client; | |
} | |
if (isset($_GET['code'])) { | |
$client->authenticate($_GET['code']); | |
$access_token = $client->getAccessToken(); | |
$refresh_token = $client->getRefreshToken(); | |
file_put_contents(TOKEN_FILENAME, json_encode(array( | |
'access_token' => $access_token, | |
'refresh_token' => $refresh_token, | |
'expires_time' => intval($access_token['expires_in']) + intval($access_token['created']) - 30, | |
))); | |
} | |
if (file_exists(TOKEN_FILENAME) && filesize(TOKEN_FILENAME) > 0) { | |
$auth = json_decode(file_get_contents(TOKEN_FILENAME), true); | |
//還沒過期 | |
if (time() < $auth['expires_time']) { | |
$client->setAccessToken($auth['access_token']); | |
$access_token = $client->getAccessToken(); | |
} else { | |
//過期了去刷過 | |
if (isset($auth['refresh_token']) && !empty($auth['refresh_token'])) { | |
$client = gapp_refresh_token($client, $auth); | |
} else { | |
echo '<a class="login" href="' . $client->createAuthUrl() . '">綁定</a>'; | |
exit; | |
} | |
} | |
} else { | |
echo '<a class="login" href="' . $client->createAuthUrl() . '">綁定</a>'; | |
exit; | |
} | |
//到這邊就是授權狀態中,可以開始請求 | |
$t = time(); | |
$FMD = date('Y-m-01', $t); | |
$TODAY = date('Y-m-d', $t); | |
$account_id = 'pub-YOUR_PUB_ID'; | |
$result = $service->accounts_reports->generate( | |
$account_id, | |
$FMD, | |
$TODAY, | |
array( | |
'metric' => array("EARNINGS", "PAGE_VIEWS", "PAGE_VIEWS_RPM", "MATCHED_AD_REQUESTS", "CLICKS", "COST_PER_CLICK", "AD_REQUESTS_COVERAGE"), | |
'dimension' => array('DOMAIN_NAME', 'DATE'), | |
'useTimezoneReporting' => true, | |
) | |
); | |
$rows = $result['rows']; | |
$domain = array(); | |
foreach ($rows as $key => $row) { | |
if (!isset($domain[$row[0]])) { | |
if (in_array($row[0], array('www.mxp.tw'))) { | |
$domain[$row[0]] = array(); | |
$domain[$row[0]][] = array('DATE' => $row[1], 'EARNINGS' => $row[2], 'PAGE_VIEWS' => $row[3], 'PAGE_VIEWS_RPM' => $row[4], 'MATCHED_AD_REQUESTS' => $row[5], 'CLICKS' => $row[6], 'COST_PER_CLICK' => $row[7], 'AD_REQUESTS_COVERAGE' => $row[8]); | |
} | |
} else { | |
if (in_array($row[0], array('www.mxp.tw'))) { | |
$domain[$row[0]][] = array('DATE' => $row[1], 'EARNINGS' => $row[2], 'PAGE_VIEWS' => $row[3], 'PAGE_VIEWS_RPM' => $row[4], 'MATCHED_AD_REQUESTS' => $row[5], 'CLICKS' => $row[6], 'COST_PER_CLICK' => $row[7], 'AD_REQUESTS_COVERAGE' => $row[8]); | |
} | |
} | |
} | |
$total = array(); | |
foreach ($domain as $key => $value) { | |
$total[$key] = array(); | |
$days = count($value); | |
//累計收入 | |
$total[$key]['T_EARNINGS'] = 0; | |
$total[$key]['AVG_EARNINGS'] = 0; | |
//累計瀏覽數 | |
$total[$key]['T_PAGE_VIEWS'] = 0; | |
$total[$key]['AVG_PAGE_VIEWS'] = 0; | |
//累計廣告曝光量 | |
$total[$key]['T_MATCHED_AD_REQUESTS'] = 0; | |
$total[$key]['AVG_MATCHED_AD_REQUESTS'] = 0; | |
//累計點擊數 | |
$total[$key]['T_CLICKS'] = 0; | |
$total[$key]['AVG_CLICKS'] = 0; | |
//累計點擊數 | |
$total[$key]['T_COST_PER_CLICK'] = 0; | |
$total[$key]['AVG_COST_PER_CLICK'] = 0; | |
//累計涵蓋率 | |
$total[$key]['T_AD_REQUESTS_COVERAGE'] = 0; | |
$total[$key]['AVG_AD_REQUESTS_COVERAGE'] = 0; | |
//累計千次瀏覽收益 | |
$total[$key]['T_PAGE_VIEWS_RPM'] = 0; | |
$total[$key]['AVG_PAGE_VIEWS_RPM'] = 0; | |
foreach ($value as $index => $data) { | |
$total[$key]['T_EARNINGS'] += floatval($data['EARNINGS']); | |
$total[$key]['T_PAGE_VIEWS'] += intval($data['PAGE_VIEWS']); | |
$total[$key]['T_CLICKS'] += intval($data['CLICKS']); | |
$total[$key]['T_MATCHED_AD_REQUESTS'] += intval($data['MATCHED_AD_REQUESTS']); | |
$total[$key]['T_COST_PER_CLICK'] += floatval($data['COST_PER_CLICK']); | |
$total[$key]['T_AD_REQUESTS_COVERAGE'] += floatval($data['AD_REQUESTS_COVERAGE']); | |
$total[$key]['T_PAGE_VIEWS_RPM'] += floatval($data['PAGE_VIEWS_RPM']); | |
if ($index == ($days - 1)) { | |
$total[$key]['TODAY'] = $data; | |
} | |
} | |
//平均收入 | |
$total[$key]['AVG_EARNINGS'] = $total[$key]['T_EARNINGS'] / $days; | |
//平均瀏覽數 | |
$total[$key]['AVG_PAGE_VIEWS'] = $total[$key]['T_PAGE_VIEWS'] / $days; | |
//平均點擊數 | |
$total[$key]['AVG_CLICKS'] = $total[$key]['T_CLICKS'] / $days; | |
//平均曝光量 | |
$total[$key]['AVG_MATCHED_AD_REQUESTS'] = $total[$key]['T_MATCHED_AD_REQUESTS'] / $days; | |
//平均CPC | |
$total[$key]['AVG_COST_PER_CLICK'] = floatval($total[$key]['T_COST_PER_CLICK'] / $days); | |
//平均涵蓋率 | |
$total[$key]['AVG_AD_REQUESTS_COVERAGE'] = floatval($total[$key]['T_AD_REQUESTS_COVERAGE'] / $days); | |
//平均CPM | |
$total[$key]['AVG_PAGE_VIEWS_RPM'] = floatval($total[$key]['T_PAGE_VIEWS_RPM'] / $days); | |
} | |
foreach ($total as $domain => $data) { | |
$separator = str_repeat('=', 10) . PHP_EOL; | |
$tday = $data['TODAY']; | |
$str = "網域:" . $domain . "({$tday['DATE']})" . PHP_EOL; | |
$str .= "今日收益:$" . $tday['EARNINGS'] . "USD" . PHP_EOL; | |
$str .= "今日瀏覽:" . $tday['PAGE_VIEWS'] . PHP_EOL; | |
$str .= "今日廣告曝光量:" . $tday['MATCHED_AD_REQUESTS'] . PHP_EOL; | |
$str .= "今日點擊:" . $tday['CLICKS'] . PHP_EOL; | |
$str .= "今日CPC:$" . $tday['COST_PER_CLICK'] . PHP_EOL; | |
$str .= "今日CPM:$" . $tday['PAGE_VIEWS_RPM'] . PHP_EOL; | |
$str .= "今日覆蓋率:" . ($tday['AD_REQUESTS_COVERAGE'] * 100) . "%" . PHP_EOL; | |
$str .= $separator . $FMD . " -> " . $TODAY . PHP_EOL . $separator; | |
//累計收入 | |
$str .= "累計收入:$" . $data['T_EARNINGS']; | |
$str .= "(平均:$" . round($data['AVG_EARNINGS'], 2) . ")USD" . PHP_EOL; | |
//累計瀏覽數 | |
$str .= "累計瀏覽數:" . $data['T_PAGE_VIEWS']; | |
$str .= "(平均:" . round($data['AVG_PAGE_VIEWS'], 2) . ")" . PHP_EOL; | |
//累計廣告曝光量 | |
$str .= "累計廣告曝光量:" . $data['T_MATCHED_AD_REQUESTS']; | |
$str .= "(平均:" . round($data['AVG_MATCHED_AD_REQUESTS'], 2) . ")" . PHP_EOL; | |
//累計點擊數 | |
$str .= "累計點擊數:" . $data['T_CLICKS']; | |
$str .= "(平均:" . round($data['AVG_CLICKS'], 2) . ")" . PHP_EOL; | |
//平均CPC | |
// $str .= "平均CPC:".$data['T_COST_PER_CLICK']; | |
$str .= "平均CPC:$" . round($data['AVG_COST_PER_CLICK'], 2) . " USD" . PHP_EOL; | |
$str .= "平均CPM:$" . round($data['AVG_PAGE_VIEWS_RPM'], 2) . " USD" . PHP_EOL; | |
//累計涵蓋率 | |
// $str .= "".$data['T_AD_REQUESTS_COVERAGE']; | |
$str .= "平均涵蓋率:" . round($data['AVG_AD_REQUESTS_COVERAGE'], 2) * 100 . "%" . PHP_EOL; | |
$d = new DateTime(date('Y-m-d H:i:s')); | |
$d->setTimeZone(new DateTimeZone('Asia/Taipei')); | |
//台灣時間1,10,13,19,23才通知 | |
if (intval($d->format('H')) == 1 || | |
intval($d->format('H')) == 10 || | |
intval($d->format('H')) == 13 || | |
intval($d->format('H')) == 19 || | |
intval($d->format('H')) == 23) { | |
line_notify($str); | |
} | |
} | |
function line_notify($msg) { | |
if ($msg == "") { | |
return; | |
} | |
$body = array( | |
'message' => PHP_EOL . $msg, | |
); | |
$headers = array( | |
'Content-Type: application/x-www-form-urlencoded', | |
'Authorization: Bearer YOUR_LINE_NOTIFY_TOKEN', | |
); | |
$url = 'https://notify-api.line.me/api/notify'; | |
$ch = curl_init(); | |
$params = array( | |
CURLOPT_URL => $url, | |
CURLOPT_RETURNTRANSFER => TRUE, | |
CURLOPT_HTTPHEADER => $headers, | |
CURLOPT_SSL_VERIFYPEER => TRUE, | |
CURLOPT_CONNECTTIMEOUT => 3, | |
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13', | |
CURLOPT_CUSTOMREQUEST => 'POST', | |
CURLOPT_POSTFIELDS => http_build_query($body), | |
); | |
curl_setopt_array($ch, $params); | |
if (!$result = curl_exec($ch)) { | |
if ($errno = curl_errno($ch)) { | |
$error_message = curl_strerror($errno); | |
error_log("cURL error ({$errno}):\n {$error_message}"); | |
curl_close($ch); | |
return FALSE; | |
} | |
} else { | |
curl_close($ch); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment