'How to validate a subscription in google play store using receipt in python

I need to validate a receipt received from an android app. I have tried using the python package pyinapp for validating in-app purchases, but end up with a "bad signature" error at validator.validate(receipt, signature):

from pyinapp import GooglePlayValidator, InAppValidationError

bundle_id = "com.yourcompany.yourapp"
api_key = "API key from the developer console"
validator = GooglePlayValidator(bundle_id, api_key)
receipt = json.dumps(
    {
        "orderId": "GPA.3371-6663-9953-88022",
        "packageName": "com.yourcompany",
        "productId": "com.yourcompany.basic.five.annually",
        "purchaseTime": 1617944948660,
        "purchaseState": 0,
        "purchaseToken": "fkefffonlgkfapblnahlokjp"
        ".AOJ1OzvaGGwTt24bMs47c98hpPQI62qdITM"
        "-uphoHzK4HQkW5locx9xDILRasO7eQTTRoGr0LwyflO2mqvnfn0fNVkZ0ipPgQ",
        "autoRenewing": true,
        "acknowledged": true,
    }
)
signature = ""  # (signature from android app)
purchases = validator.validate(receipt, signature)
process_purchases(purchases)


Solution 1:[1]

I have used google-api-python-client==2.1.0:

from google.oauth2 import service_account
from app.settings import GOOGLE_PLAY_STORE_KEY
import googleapiclient.discovery


def validate_subscription_in_google_play_store(subscription, token):
    credentials = service_account.Credentials.from_service_account_file(
        GOOGLE_PLAY_STORE_KEY
    )
    response = (
        googleapiclient.discovery.build(
            "androidpublisher", "v3", credentials=credentials
        )
        .purchases()
        .subscriptions()
        .get(packageName="com.abc", subscriptionId=subscription, token=token)
        .execute()
    )
    return response

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Florian