如何在网页中以弹窗方式安全集成 PHPMailer OAuth2 授权流程

phpmailer 的 get_oauth_token.php 会触发重定向,无法直接加载到指定 div 中;但可通过弹窗 + postmessage 实现无刷新授权,保持主页面状态不变。
PHPMailer 自带的 ✅ 正确方案:使用 弹窗(popup)+ 跨窗口通信 示例实现: 1. 主页面(如 admin/index.php)中触发授权: 2. 修改
get_oauth_token.php 脚本(官方源码)本质上是一个服务端 OAuth2 授权引导程序:它生成 Google 认证 URL,并通过 header('Location: ...') 强制跳转。这种 HTTP 重定向天然无法嵌入 或 iframe(现代浏览器会阻止跨域重定向嵌入,且 iframe 内重定向后父页面无法可靠监听状态)。因此,“将授权流程载入指定 div”在技术上不可行。
核心思路是:主页面打开授权弹窗 → 用户完成 Google 登录与授权 → 弹窗重定向回你的 redirect_uri(如 /admin/oauth-callback.php)→ 弹窗脚本通过 window.opener.postMessage() 将授权码(code)或令牌结果发送给主页面 → 主页面接收后关闭弹窗并继续后续流程。<button>连接 Gmail 账户</button>
<div></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:

