You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django-React集成Google Calendar API遇redirect_uri_mismatch错误求助

解决Google Calendar API的redirect_uri_mismatch错误

以下是针对你的场景的排查和解决步骤:

1. 严格匹配redirect_uri的每一个字符

不管是在Google API控制台配置的重定向URI,还是Django代码里指定的redirect_uri,或是Postman请求中传递的参数,三者必须完全一致:

  • 检查协议(http/https)、端口、路径,比如你的Django回调地址如果是http://localhost:8000/api/calendar/callback,必须一字不差复制到控制台的重定向URI列表中,不能多斜杠、少路径。
  • Postman测试时,注意不要使用默认的https://oauth.pstmn.io/v1/callback,要替换成你的Django回调地址。

2. 确认凭证类型为Web应用

在Google API控制台创建凭证时,必须选择Web应用类型:

  • 授权JavaScript来源填写http://localhost:3000(你的React前端地址)
  • 授权重定向URI填写Django的回调地址(比如http://localhost:8000/api/calendar/callback)

3. 清除旧授权缓存

Google OAuth2会缓存旧的授权配置,导致新配置不生效:

  • 访问Google账号权限页面,移除你的应用的授权权限
  • 在Postman中清除对应的OAuth2会话,重新发起授权请求

4. 检查Django代码中的redirect_uri参数

确保你在构建Google授权URL时,指定的redirect_uri和控制台配置完全一致,示例代码如下:

from rest_framework.views import APIView
from rest_framework.response import Response
from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
import os

# 开发环境允许HTTP,生产环境需移除
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

class CalendarAuthAPI(APIView):
    def get(self, request):
        flow = Flow.from_client_secrets_file(
            'path/to/credentials.json',
            scopes=['https://www.googleapis.com/auth/calendar'],  # 包含创建事件的权限
            redirect_uri='http://localhost:8000/api/calendar/callback'  # 与控制台一致
        )
        auth_url, state = flow.authorization_url(
            access_type='offline',
            include_granted_scopes='true'
        )
        return Response({"auth_url": auth_url})

class CalendarCallbackAPI(APIView):
    def get(self, request):
        flow = Flow.from_client_secrets_file(
            'path/to/credentials.json',
            scopes=['https://www.googleapis.com/auth/calendar'],
            redirect_uri='http://localhost:8000/api/calendar/callback'
        )
        flow.fetch_token(code=request.GET.get('code'))
        credentials = flow.credentials
        
        # 调用API获取事件示例
        service = build('calendar', 'v3', credentials=credentials)
        events = service.events().list(calendarId='primary', maxResults=10).execute()
        return Response({"events": events.get('items', [])})

5. 遵循正确的授权流程

你的场景下,正确的授权流程应该是:

  1. React前端跳转至Django提供的授权URL
  2. 用户在Google授权页面完成授权,Google重定向至Django回调接口
  3. Django获取授权码并兑换access_token,之后调用Calendar API实现事件的获取或创建

内容的提问来源于stack exchange,提问作者Juan Taylor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:57:36