Google OAuth fetching token for API use – Invalid Grant Error

I’m trying to use google’s calendar API and I’m so lost. I figured out how to get authentication the first time around, when I send the user to approve the access scope, but I can’t figure out how to get the credentials I need to perform any other actions once the session for that original authorization goes away. Here is all my code around connection to google.

def connect_to_google(user_id):

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(CLIENT_SECRETS_FILE, scopes=['https://www.googleapis.com/auth/calendar.app.created'])
    flow.redirect_uri = 'https://tb-read.com/createcalendar'
    authorization_url, state = flow.authorization_url(access_type="offline", include_granted_scopes="true", prompt="consent")
    session['state'] = state

    return redirect(authorization_url)```

@app.route('/createcalendar')
def create_calendar():
    """Create a new google calendar for the user"""

    if not g.user: 
        flash ('Please log in', 'danger')
        return redirect('/') 
    
    code = request.args.get('code')
    state = session['state']
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(CLIENT_SECRETS_FILE, scopes=['https://www.googleapis.com/auth/calendar.app.created'], state=state)
    flow.redirect_uri = url_for('create_calendar', _external=True)
    authorization_response = request.url
    flow.fetch_token(authorization_response=authorization_response)
    credentials = flow.credentials
    session['credentials'] = {
        'token': credentials.token,
        'refresh_token': credentials.refresh_token,
        'token_uri': credentials.token_uri,
        'client_id': credentials.client_id, 
        'client_secret': credentials.client_secret,
        'scopes': credentials.scopes
    }

    service = build('calendar', 'v3', credentials=credentials)
    calendar = {
        'summary': 'TB Read Calendar'
    }
    created_calendar = service.calendars().insert(body=calendar).execute()
    user = db.session.execute(db.select(User).where(User.user_id == g.user.user_id)).scalar()
    user.calendar_id = created_calendar['id']
    user.google_code = code
    db.session.add(user)
    db.session.commit()
    print('****************************')
    print(user.calendar_id)
    service.close()

    return redirect(f'/users/{g.user.user_id}/calendar')

@app.route('/api/posting', methods=['POST'])
def schedule_posting_days():
    """Schedule a user's posting schedule on the google calendar"""

    if not g.user: 
        flash ('Please log in', 'danger')
        return redirect('/') 
    
    last_post_date = request.json['lastPostDate']
    posting_frequency = request.json['postingFrequency']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(CLIENT_SECRETS_FILE, scopes=['https://www.googleapis.com/auth/calendar.app.created'])
    authorization_response = request.url
    flow.fetch_token(authorization_response=authorization_response, code=g.user.google_code)
    credentials = flow.credentials
    session['credentials'] = {
        'token': credentials.token,
        'refresh_token': credentials.refresh_token,
        'token_uri': credentials.token_uri,
        'client_id': credentials.client_id, 
        'client_secret': credentials.client_secret,
        'scopes': credentials.scopes
    }

    service = build('calendar', 'v3', credentials=credentials)
    ## Check if a posting date event currently exists
    existing_posting_event = db.session.execute(db.select(Event).where(Event.user_id == g.user.user_id).where(Event.eventcategory == 'Posting')).scalar()
    ## Delete remaining recurring posting events
    if existing_posting_event.google_event_id: 
        post_event = service.events().get(calendarId=g.user.calendar_id, eventId = existing_posting_event.google_event_id).execute()
        today = date.today()
        post_event['recurrance'] = [f'RRULE: FREQ=DAILY; COUNT=g.user.posting_frequency; UNTIL={today}']
        service.events().update(calendarId=g.user.calendar_id, EventId = existing_posting_event.google_event_id, body=post_event).execute()
    ## Add new posting date event
    event = {
        'summary': 'Posting Day',
        'start.date': last_post_date,
        'end.date': last_post_date,
        'recurrence': [f'RRULE: FREQ=DAILY; COUNT={posting_frequency}']
    }
    posting_day = service.events().insert(calendarId = g.user.calendar_id, body=event).execute()
    print('**************************')
    print(posting_day)
    service.close()
    ## Update user profile
    if g.user.posting_frequency != posting_frequency:
        user = db.session.execute(db.select(User).where(User.user_id == g.user.user_id)).scalar()
        user.posting_frequency = posting_frequency
        db.session.add(user)
        db.session.commit()

    return jsonify({'success': 'Posting Event Changed'})

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật