
phpmailer 的 get_oauth_token.php 会触发重定向,无法直接加载到指定 div 中;但可通过弹窗 + postmessage 实现无刷新授权,保持主页面状态不变。
phpmailer 的 get_oauth_token.php 会触发重定向,无法直接加载到指定 div 中;但可通过弹窗 + postmessage 实现无刷新授权,保持主页面状态不变。
PHPMailer 自带的 ✅ 正确方案:使用 弹窗(popup)+ 跨窗口通信 示例实现: 1. 主页面(如 admin/index.php)中触发授权: 使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。 2. 修改 get_oauth_token.php 脚本(官方源码)本质上是一个服务端 OAuth2 授权引导程序:它生成 Google 认证 URL,并通过 header('Location: ...') 强制跳转。这种 HTTP 重定向天然无法嵌入
核心思路是:主页面打开授权弹窗 → 用户完成 Google 登录与授权 → 弹窗重定向回你的 redirect_uri(如 /admin/oauth-callback.php)→ 弹窗脚本通过 window.opener.postMessage() 将授权码(code)或令牌结果发送给主页面 → 主页面接收后关闭弹窗并继续后续流程。
<button id="oauth-btn">连接 Gmail 账户</button>
<div id="auth-status"></div>
<script>
document.getElementById('oauth-btn').addEventListener('click', () => {
const popup = window.open(
'/admin/get_oauth_token.php?state=' + encodeURIComponent(Date.now()),
'gmail_auth',
'width=600,height=700,scrollbars=yes'
);
// 监听弹窗发来的消息
window.addEventListener('message', (e) => {
if (e.source === popup && e.data.type === 'OAUTH_CALLBACK') {
document.getElementById('auth-status').innerHTML =
`<p>✅ 授权成功!Code: ${e.data.code}`;
popup.close();
// 此处可发起 AJAX 请求,用 code 换取 access_token 并保存
fetch('/admin/exchange-token.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code: e.data.code })
}).then(r => r.json()).then(console.log);
}
});
});
</script>
get_oauth_token.php 的回调页(推荐新建 /admin/oauth-callback.php):
在用户授权完成后,Google 会重定向至此页(需在 Google Cloud Console 中配置为合法 redirect_uri)。该页不渲染 HTML,仅输出轻量 JS:redirect_uri
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










