调用Google My Business API获取本地帖子时遇401错误求助
问题分析与解决:Google My Business Profile API 401认证错误
问题背景
调用Google My Business Profile API的accounts.locations.localPosts/list方法,通过Place ID获取商家公开的LocalPosts并嵌入Wix网站展示时,浏览器返回401错误。疑惑为何获取公开商家信息也需要OAuth2.0认证,当前代码直接用API Key作为Bearer Token,还错误地将API Key填在了accounts路径参数中。
核心问题解析
- API强制认证规则:Google My Business Profile API的所有接口(包括获取公开LocalPosts)都要求OAuth2.0认证,哪怕是公开信息。这是平台为了防止API滥用、确保请求发起者身份合规的强制要求,并非仅针对私有数据。
- 代码中的两处关键错误:
- 路径参数错误:
accounts/${apiKey}是错误写法,此处需填写商家的Google账号ID,而非API Key。 - 认证方式错误:API Key不能作为Bearer Token使用,Bearer Token必须是通过OAuth2.0流程获取的访问令牌(Access Token),API Key仅适用于部分公开API(比如Places API的部分接口),但My Business API不支持这种认证方式。
- 路径参数错误:
修正方案与步骤
1. 完成OAuth2.0授权流程
由于是前端嵌入Wix,推荐使用授权码流程(Authorization Code Flow with PKCE),避免前端暴露客户端密钥:
- 在Google Cloud控制台创建OAuth客户端ID,设置授权回调地址为你的Wix网站域名。
- 引导商家完成授权,获取授权码后兑换成Access Token(同时会得到Refresh Token用于后续刷新令牌)。
2. 修正后的请求代码
<html> <head> <title>Google My Business Local Posts</title> </head> <body> <h1>Local Posts</h1> <div id="localPosts"></div> <script> // 替换为实际获取的OAuth2.0访问令牌 const accessToken = 'YOUR_OAUTH_ACCESS_TOKEN'; // 替换为商家的Google账号ID const accountId = 'YOUR_BUSINESS_ACCOUNT_ID'; const placeId = 'PLACEID'; async function fetchLocalPosts() { try { const response = await fetch(`https://mybusiness.googleapis.com/v4/accounts/${accountId}/locations/${placeId}/localPosts`, { headers: { 'Authorization': `Bearer ${accessToken}` } }); if (response.ok) { const data = await response.json(); const localPostsContainer = document.getElementById('localPosts'); // API返回的是包含localPosts数组的对象,需正确取值 if (data.localPosts && data.localPosts.length > 0) { data.localPosts.forEach(post => { const postElement = document.createElement('div'); postElement.classList.add('post'); // 处理标题(部分帖子可能无title字段) if (post.title) { const titleElement = document.createElement('h2'); titleElement.textContent = post.title; postElement.appendChild(titleElement); } // 处理内容 if (post.content) { const contentElement = document.createElement('p'); contentElement.textContent = post.content; postElement.appendChild(contentElement); } localPostsContainer.appendChild(postElement); }); } else { localPostsContainer.textContent = '暂无本地帖子'; } } else { console.error('请求失败:', response.statusText); const errorData = await response.json(); console.error('错误详情:', errorData); } } catch (error) { console.error('获取本地帖子出错:', error); } } fetchLocalPosts(); </script> </body> </html>
3. Wix网站适配注意事项
- Wix可能存在跨域请求限制,建议在Wix后台将Google My Business API域名添加到允许列表,或使用Wix官方的
wix-fetch工具发起请求,避免CORS报错。 - Access Token存在过期时间,建议在后端处理令牌刷新逻辑,不要在前端暴露Refresh Token,防止安全风险。
内容的提问来源于stack exchange,提问作者sytez
相关产品推荐
相关产品推荐

