Authenticate a GET request to Google Play Purchase API with service account python

Tom*_*652 5 python android in-app-purchase google-api-python-client google-play-developer-api

I need to verify purchases of my android App from my AWS lambda in python.

I have seen many posts of how to do so and the documentation and here is the code I have written :

url = f"{google_verify_purchase_endpoint}/{product_id}/tokens/{token}"
response = requests.get(url=url)
data = response.json()
logging.info(f"Response from Google Play API : {data}")
Run Code Online (Sandbox Code Playgroud)

When I do so, it throws a 401 status code not allowed. Alright, I have created a service account to allow the request with OAuth, but how can I use it to allow the request ?

Unfortunately I can't use the google-api-python-client as mentioned here which is too big for my AWS lambda maximum size of 250Mb unzipped package.

So my question is to use the service account with a simple GET requests or how can I authenticate automatically without the google-api-python-client ?

Thanks in advance

小智 2

先决条件和假设

您似乎已经设置了一个服务帐户,但在使用 verify_purchase 端点之前需要获取 JSON Web 令牌 (JWT)。此处记录了生成 JWT 的过程。您应该阅读本文以了解以下代码的作用。

我注意到您有存储限制,但您几乎肯定需要一个额外的库来处理令牌生成的加密方面。PyJwt 相当小(包括它的要求)。

我们先安装这个:

pip3 install PyJwt
Run Code Online (Sandbox Code Playgroud)

获取私钥

接下来,让我们从 Google Cloud 获取我们的服务帐户私钥。

Open your project in Google Cloud.

Go to "APIs & Services".

Go to "Credentials".

Click "Service Account".

Find your Service Account and Select "Manage Keys".

Select "Create new key" from the "ADD KEY" drop down.

Select JSON.

Save this JSON file to a secure location accessible by your script.
Run Code Online (Sandbox Code Playgroud)

投入使用

现在我们可以开始编写 Python 脚本了。这是一个帮助您入门的示例(您应该在将其投入生产之前查看它):

pip3 install PyJwt
Run Code Online (Sandbox Code Playgroud)

使用我们的访问令牌

然后可以将其access_token用作您项目的 JWT 承载者。请注意,我已将token变量更改为subscription_token原始帖子中的变量,以明确它与此身份验证机制无关。(它指的是“购买订阅时提供给用户设备的令牌。”根据您提供的文档。)

Open your project in Google Cloud.

Go to "APIs & Services".

Go to "Credentials".

Click "Service Account".

Find your Service Account and Select "Manage Keys".

Select "Create new key" from the "ADD KEY" drop down.

Select JSON.

Save this JSON file to a secure location accessible by your script.
Run Code Online (Sandbox Code Playgroud)

结束语

这只是为了介绍如何在没有 SDK 的情况下针对 Google Cloud API 进行身份验证。最终,您对项目的安全性负责,阅读本文的任何其他人都应该尽可能使用 SDK。我还建议您将上述代码整理为后续函数,以便在适当的情况下调用。

祝您项目的其余部分一切顺利!