如何通过OAuth2服务账号调用Google Android Publisher API获取应用星级数?
使用服务账号调用Google Play Android Publisher API获取应用星级数量
别担心,这个问题其实很好解决!你已经选对了服务器到服务器的服务账号方案,虽然官方示例是针对SQL Admin的,但适配到Android Publisher API只需要几个小调整就行。
第一步:先搞定权限配置(非常重要!)
在写代码之前,你得确保服务账号有足够的权限:
- 在Google Cloud控制台,给你的服务账号添加Android Publisher API的访问权限(至少是只读权限)。
- 更关键的是,登录Google Play Console,找到你的应用→进入「用户和权限」页面,把服务账号的邮箱地址添加为项目成员,授予「查看应用信息」或者更高的权限(没有这一步,API会直接返回403权限错误)。
第二步:修正Scope并补全代码
你代码里的Scope没写完,Android Publisher的正确只读Scope是https://www.googleapis.com/auth/androidpublisher.readonly(如果只需要读取星级数据,这个足够安全)。下面是完整的可运行代码示例:
from google.oauth2 import service_account from googleapiclient.discovery import build # 替换成你的服务账号密钥文件路径 SERVICE_ACCOUNT_FILE = 'path/to/your/service-account-key.json' # 只读权限的Scope,满足获取星级需求 SCOPES = ['https://www.googleapis.com/auth/androidpublisher.readonly'] # 替换成你的应用包名 PACKAGE_NAME = 'com.your.app.package.name' def fetch_app_star_ratings(): # 初始化服务账号凭证 credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) # 构建Android Publisher v3服务实例 try: service = build('androidpublisher', 'v3', credentials=credentials) # 调用API获取应用信息(包含星级统计) app_details = service.apps().get(packageName=PACKAGE_NAME).execute() aggregate_rating = app_details.get('aggregateRating', {}) # 提取各星级的具体数量 star_counts = { "1星": aggregate_rating.get('oneStarRatings', 0), "2星": aggregate_rating.get('twoStarRatings', 0), "3星": aggregate_rating.get('threeStarRatings', 0), "4星": aggregate_rating.get('fourStarRatings', 0), "5星": aggregate_rating.get('fiveStarRatings', 0) } print("应用各星级数量统计:") for star, count in star_counts.items(): print(f"{star}: {count}") return star_counts except Exception as e: print(f"调用API出错:{str(e)}") return None # 执行函数 if __name__ == '__main__': fetch_app_star_ratings()
额外注意事项
- 先安装依赖包:运行
pip install google-auth google-api-python-client - 服务账号密钥文件要妥善保管,别泄露到公共代码仓库里
- 如果需要获取更详细的评论数据,才需要用
reviews.list接口,而获取星级数量用apps.get就足够了,效率更高
内容的提问来源于stack exchange,提问作者Chan
相关产品推荐
相关产品推荐

