.NET 8网站验证Google Play应用购买状态遇权限问题求助
我在Google Play发布了一款应用,希望为已购买该应用的用户开放我的网站访问权限。已完成用户Google账号登录功能,但无法获取特定Google账号是否购买了我的应用的信息。
我在.NET 8后端应用中尝试了以下代码:
public async Task<bool> GetGooglePurchaseStatus(string email) { string packageName = "com.packagename"; string productId = "xxxxxxxxxxxxxxxxxxxx"; string fileName = "gapi.json"; string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets"); string filePath = Path.Combine(folderPath, fileName); var credential = GoogleCredential.FromFile(filePath); var service = new AndroidPublisherService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = packageName }); var request = service.Purchases.Products.Get(packageName, productId, email); var purchase = await request.ExecuteAsync(); return purchase.PurchaseState == 0; // 0 means purchased }
运行后出现如下错误:
The service androidpublisher has thrown an exception.
HttpStatusCode is Unauthorized.
Google.Apis.Requests.RequestError
The current user has insufficient permissions to perform the requested operation. [401]
Errors [
Message[The current user has insufficient permissions to perform the requested operation.] Location[ - ] Reason[permissionDenied] Domain[androidpublisher]
]
我确定在Google Cloud和/或Google Play Console的设置中遗漏了某些配置,请问需要设置哪些权限,以及在哪里设置?
已在Google Cloud新建项目,并创建了服务账号,下载了凭证json文件。
1. 启用Android Publisher API
在Google Cloud控制台的目标项目中,搜索Android Publisher API,点击启用该API。
2. 为服务账号分配Play Console权限
- 打开Google Play Console,进入对应应用的管理页面
- 点击左侧菜单的用户和权限
- 切换到服务账号标签页
- 点击邀请新用户,输入服务账号的邮箱(可从下载的
gapi.json文件中找到client_email字段) - 为该服务账号分配查看应用权限(遵循最小权限原则,若需财务相关数据可选择对应权限),完成保存
3. 修正API调用参数
代码中使用email作为Purchases.Products.Get的第三个参数是错误的,该参数需要传入购买令牌(purchaseToken)。你需要从Android客户端获取用户购买产品时返回的purchaseToken,再将其传给后端接口,而非直接使用用户邮箱查询购买状态。
内容的提问来源于stack exchange,提问作者Mårten Swärd

