Попытка получить отзывы в Google с помощью Python / Django потерпела неудачу от ChatGpt, Claude и DeepSeek

У меня есть приложение django, в котором пользователь входит в систему Google и дает разрешение на доступ к бизнес-профилям Google для получения отзывов. Я храню эти токены Google в своей базе данных. Но когда я пытаюсь получить отзывы Google, это не удается. Он даже не может получить данные бизнес-профиля Google. Я пробовал Chatgpt, Claude, Deepseek, но безуспешно. Вот мой код на django и python, который я пробовал ранее.

Код входа в Google в Django:

Код 1 для получения отзывов Google по 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}")

Код 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()

Код 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)

У меня есть еще коды. В каждом из них было указано, что бизнес-данных нет, и произошел сбой. Помогите мне, если можете, пожалуйста. Спасибо».

Вернуться на верх