admob 廣告開發者報表 api

廣告是移動應用很是好的變現模式,做爲開發者常常會接不少家的廣告平臺,每一個廣告平臺都有本身的報表系統,就會有一個各個平臺數據彙總分析的需求,首先第一步就須要從各個廣告平臺獲取數據,除了在web頁面提供基本的數據導出功能,基本上各個平臺都會提供 api 來方便數據拉取的自動化。python

admob 是 google 的移動開發者廣告平臺,一樣也提供了完備的 api 來獲取報表數據web

建立 API 憑證

報表 api 使用 oauth 2.0 受權,須要先開通雲平臺帳號,須要填一下帳單信息。開通帳號後,在平臺上建立一個 oauth 2.0 的憑證json

google oauth 受權

建立完成後,下載JSON 祕鑰文件,保存爲 client_secrets.jsonapi

使用 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
)

調用服務 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: 使用帳戶所在的時區app

參考代碼

代碼依賴了一個 client_secrets.json 的受權文件ide

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()

參考連接

轉載請註明出處
本文連接: http://www.hatlonely.com/2018...
相關文章
相關標籤/搜索