[Python] POST request to google analytics API with encrypted parameters throws Invalid grant...

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to generate the Access Token using Refresh token from Google Analytics API. The request which I am trying to send is encrypted using Python libraries. When I run the below code, I am getting

    {'error': 'unsupported_grant_type', 'error_description':'Invalid grant_type: '}

    When I run this code without encrypting the parameters, my request works fine without any issues and able to get the access token as well. I am not really sure what I am missing here. Kindly help on this issue and suggest some solutions.

    import os
    import requests
    import json
    import base64
    import random
    from Crypto import Random
    from Crypto.Cipher import AES
    from Crypto.Random import get_random_bytes
    from Crypto.Util.padding import pad,unpad
    import secrets

    key= os.urandom(16)
    iv = Random.new().read(AES.block_size)


    def encrypt_data(key, data):
    BS = AES.block_size
    pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode()
    cipher = AES.new(key, AES.MODE_CBC, iv)
    encrypted_data = base64.b64encode(cipher.encrypt(pad(data)))
    return encrypted_data


    base_url = "https://accounts.google.com"
    client_Id = "XXXXX"
    client_secret = "YYYYY"
    grant_type = "refresh_token"
    refresh_token = "ZZZZZZ"
    access_type="offline"

    data = {"grant_type":grant_type,
    "client_id":client_Id,
    "client_secret":client_secret,
    "refresh_token":refresh_token,
    "access_type":access_type
    }

    encode_string = json.dumps(data).encode("utf-8")
    response = requests.post(base_url+"/o/oauth2/token?",params=encrypt_data(key,encode_string)).json()
    print(response.content)

    Continue reading...

Compartilhe esta Página