admob 廣告開發者報表 api
廣告是移動應用非常好的變現模式,作為開發者經常會接很多家的廣告平臺,每個廣告平臺都有自己的報表系統,就會有一個各個平臺數據彙總分析的需求,首先第一步就需要從各個廣告平臺獲取資料,除了在web頁面提供基本的資料匯出功能,基本上各個平臺都會提供 api 來方便資料拉取的自動化。
admob 是 google 的移動開發者廣告平臺,同樣也提供了完備的 api 來獲取報表資料
建立 API 憑證
報表 api 使用 oauth 2.0 授權,需要先開通雲平臺賬號,需要填一下賬單資訊。開通賬號後,在平臺上建立一個 oauth 2.0 的憑證
建立完成後, 下載JSON
祕鑰檔案,儲存為 client_secrets.json
使用 google api 的 python 庫
sudo pip3 install google-api-python-client sudo pip3 install oauth2client
初始化服務
from apiclient import sample_tools scope = ['https://www.googleapis.com/auth/adsense.readonly'] client_secrets_file = 'client_secrets.json' service, _ = sample_tools.init( '', 'adsense', 'v1.4', __doc__, client_secrets_file, parents=[], scope=scope )
呼叫服務 ofollow,noindex">api
results = service.accounts().reports().generate( accountId='pub-131xxxxxxxxxxxxx', startDate=start.strftime('%Y-%m-%d'), endDate=end.strftime('%Y-%m-%d'), metric=metric, dimension=dimension, useTimezoneReporting=True, ).execute()
accountId
: 在 admob 平臺的首頁上
https://apps.admob.com/v2/home 點選自己的頭像,
釋出商 ID
就是
accountId
metric
: 指標項,點選、展示、收入等
dimension
: 維度,日期、app、廣告位、國家等
startDate
: 開始日期,yyyy-mm-dd 格式
endDate
: 結束時間,yyyy-mm-dd 格式
useTimezoneReporting
: 使用賬戶所在的時區
參考程式碼
程式碼依賴了一個 client_secrets.json
的授權檔案
import json import datetime import argparse from apiclient import sample_tools def collect(start=None, end=None): if not start: start = datetime.datetime.now() - datetime.timedelta(days=1) if not end: end = start scope = ['https://www.googleapis.com/auth/adsense.readonly'] client_secrets_file = 'client_secrets.json' service, _ = sample_tools.init( '', 'adsense', 'v1.4', __doc__, client_secrets_file, parents=[], scope=scope ) dimension = [ "DATE", "APP_NAME", "APP_PLATFORM", "AD_UNIT_NAME", "AD_UNIT_ID", "COUNTRY_CODE" ] metric = [ "AD_REQUESTS", "CLICKS", "INDIVIDUAL_AD_IMPRESSIONS", "EARNINGS", "REACHED_AD_REQUESTS_SHOW_RATE" ] results = service.accounts().reports().generate( accountId='pub-131xxxxxxxxxxxxx', startDate=start.strftime('%Y-%m-%d'), endDate=end.strftime('%Y-%m-%d'), metric=metric, dimension=dimension, useTimezoneReporting=True, ).execute() headers = [i.lower() for i in dimension + metric] datas = [] for row in results.get('rows'): data = {} for i in range(len(row)): data[headers[i]] = row[i] datas.append(data) return datas def transform(datas): for data in datas: # 資料轉化 pass return datas def serialize(datas): for data in datas: print(json.dumps(data)) def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="""Example: python3 admob.py -s 20181025 -e 20181028 """ ) parser.add_argument( '-s', '--start', type=lambda d: datetime.datetime.strptime(d, '%Y%m%d'), help='start time', default=None ) parser.add_argument( '-e', '--end', type=lambda d: datetime.datetime.strptime(d, '%Y%m%d'), help='end time', default=None ) args = parser.parse_args() serialize(transform(collect(args.start, args.end))) if __name__ == '__main__': main()