[Python] Trying to pull Google Reviews with Python/Django, failed by ChatGpt, Claude and...

Discussão em 'Python' iniciado por Stack, Fevereiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    I have a django app where user sign’s in with google and gives permission to access google business profiles to pull reviews. I store those google tokens in my database. But when I try to pull google reviews, it can not pull. It can not even get google business profile data. I tried Chatgpt, Claude, Deepseek but failed. Here is my django and python code what I tried before.

    Google sign in code in Django:

    def google_integration(request, location_id):
    app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL
    gb_url = request.GET.get('gb_url')
    gb_incentive = request.GET.get('gb_incentive')

    params = f'?location={location_id}&redirect_url={request.META.get("HTTP_REFERER")}'
    params += f'&gb_url={gb_url}'
    params += f'&gb_incentive={gb_incentive}'

    return redirect(app_url + reverse('business:google_integration_from_origin') + params)


    #@subscribed_business_only
    def google_integration_from_origin(request):
    location_id = request.GET.get('location')
    previous_page = request.GET.get('redirect_url')
    gb_url = request.GET.get('gb_url')
    gb_incentive = request.GET.get('gb_incentive')

    if not location_id:
    messages.error(request, 'Location not found')
    return redirect('dashboard:index')

    app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL

    flow = Flow.from_client_secrets_file(
    'client_secrets.json',
    scopes=['https://www.googleapis.com/auth/business.manage'],
    redirect_uri=app_url + reverse('business:google_callback')
    )

    auth_url, state = flow.authorization_url(
    access_type='offline',
    include_granted_scopes='true',
    prompt='consent' # Forces Google to show the permission screen again
    )

    request.session['google_auth_state'] = state
    request.session['location_id'] = location_id
    request.session['google_callback_redirect_url'] = previous_page or reverse('dashboard:index')
    request.session['gb_url'] = gb_url
    request.session['gb_incentive'] = gb_incentive
    return redirect(auth_url)

    # @subscribed_business_only
    def google_callback(request):
    state = request.session.get('google_auth_state')
    location_id = request.session.get('location_id')
    app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL
    gb_url = request.session.get('gb_url')
    gb_incentive = request.session.get('gb_incentive')

    flow = Flow.from_client_secrets_file(
    'client_secrets.json',
    scopes=['https://www.googleapis.com/auth/business.manage'],
    state=state
    )

    flow.redirect_uri = app_url + reverse('business:google_callback')

    # Fetch the token using the authorization response
    authorization_response = request.build_absolute_uri()
    flow.fetch_token(authorization_response=authorization_response)

    credentials = flow.credentials

    if not location_id:
    messages.error(request, 'Location is required.')
    return redirect(reverse('dashboard:index'))

    integration_platform = business_models.IntegrationPlatform.objects.get(location_id=location_id, name='Google My Business')
    integration_platform.url = gb_url
    integration_platform.incentive = gb_incentive
    integration_platform.save()

    # Save the credentials to the database
    business_models.GoogleCredential.objects.create(
    access_token=credentials.token,
    refresh_token=credentials.refresh_token,
    # token_expiry=credentials.expiry,
    location_id=location_id,
    client_id=credentials.client_id,
    client_secret=credentials.client_secret,
    )

    redirect_url = request.session.get('google_callback_redirect_url')
    return redirect(redirect_url)


    Code 1 to pull google reviews by API:

    import requests
    import gcred_hb

    # Replace with your valid access token
    ACCESS_TOKEN = gcred_hb.access_token

    def get_business_accounts():
    """Fetches all business accounts associated with the authenticated user."""
    url = "https://mybusiness.googleapis.com/v4/accounts"
    headers = {"Authorization": f"Bearer {ACCESS_TOKEN}", "Accept": "application/json"}

    response = requests.get(url, headers=headers)

    if response.status_code == 200:
    return response.json().get("accounts", [])
    else:
    print(f"Error fetching accounts: {response.status_code} - {response.text}")
    return []

    def get_business_locations(account_name):
    """Fetches all business locations associated with a business account."""
    url = f"https://mybusiness.googleapis.com/v4/{account_name}/locations"
    headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"}

    response = requests.get(url, headers=headers)

    if response.status_code == 200:
    return response.json().get("locations", [])
    else:
    print(f"Error fetching locations: {response.status_code} - {response.text}")
    return []

    def format_business_info(location):
    """Formats business information for readability."""
    return {
    "Business Name": location.get("title", "N/A"),
    "Address": location.get("storefrontAddress", {}).get("addressLines", ["N/A"]),
    "Phone": location.get("primaryPhone", "N/A"),
    "Website": location.get("websiteUrl", "N/A"),
    "Google Maps URL": location.get("metadata", {}).get("mapsUri", "N/A"),
    }

    if __name__ == "__main__":
    # Step 1: Get Business Accounts
    accounts = get_business_accounts()

    if not accounts:
    print("No business accounts found.")
    else:
    for account in accounts:
    print(f"\nFetching locations for business account: {account['name']}")
    locations = get_business_locations(account['name'])

    if not locations:
    print("No locations found.")
    else:
    for location in locations:
    business_info = format_business_info(location)
    print("\nBusiness Information:")
    for key, value in business_info.items():
    print(f"{key}: {value}")


    Code 2

    import os, requests
    from django.shortcuts import redirect
    from django.http import HttpResponse
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import Flow
    from googleapiclient.discovery import build
    from google.auth.transport.requests import Request
    from google.auth.exceptions import RefreshError


    def get_reviews():
    credentials = Credentials(
    token='ya29.a0AXeO80SUjgYN...',
    refresh_token='1//09JlmJffhLkG8CgYIAR....',
    token_uri='https://oauth2.googleapis.com/token',
    client_id='541810874420-sdrc9d.apps.googleusercontent.com',
    client_secret='GOCSPX-Z713td7....',
    scopes= ['https://www.googleapis.com/auth/business.manage']
    )

    if not credentials.valid:
    if credentials.expired and credentials.refresh_token:
    try:
    credentials.refresh(Request())
    except RefreshError:
    return HttpResponse('Failed to refresh credentials. Please sign in again.')

    service = build('mybusiness', 'v4', credentials=credentials)
    accounts = service.accounts().list().execute()
    account_name = accounts['accounts'][0]['name']
    reviews = service.accounts().locations().reviews().list(parent=account_name).execute()

    return HttpResponse(f"Reviews: {reviews}")


    get_reviews()


    Code 3

    from googleapiclient.discovery import build
    from google.auth.transport.requests import Request
    from google.auth import credentials
    import gcred_hb

    # If token is expired, refresh it using the refresh token


    def refresh_credentials():
    from google.auth import credentials
    credentials = credentials.Credentials.from_authorized_user_info(
    refresh_token=gcred_hb.refresh_token,
    client_id=gcred_hb.client_id,
    client_secret=gcred_hb.client_secret
    )

    # Refresh the credentials if expired
    if credentials.expired:
    credentials.refresh(Request())

    return credentials

    def get_location_id(credentials):
    """Get the location ID for the authenticated user's business."""
    service = build('mybusinessbusinessinformation', 'v1', credentials=credentials)

    # List locations associated with the user's account
    locations = service.accounts().locations().list(parent='accounts/{account_id}').execute()

    for location in locations['locations']:
    print(f"Location Name: {location['locationName']}")
    print(f"Location ID: {location['name']}") # This is the Location ID
    return location['name'] # Return Location ID

    def fetch_reviews(credentials, location_id):
    """Fetch reviews from Google Business Profile for a given location."""
    service = build('mybusinessbusinessinformation',
    'v1', credentials=credentials)

    # Fetch reviews for the given location
    reviews = service.accounts().locations().reviews().list(
    parent=f'accounts/{location_id}').execute()

    if 'reviews' in reviews:
    for review in reviews['reviews']:
    print(f"Author: {review['authorName']}")
    print(f"Rating: {review['starRating']}")
    print(f"Review: {review['comment']}")
    print(f"Time: {review['createTime']}")
    print('-' * 50)
    else:
    print("No reviews found.")


    cred = refresh_credentials()
    location_id = get_location_id(cred)

    print(location_id)


    I have more codes. Every single one of them said no business data and failed. Help me out if you can, please. Thank you.

    Continue reading...

Compartilhe esta Página