OAuth2.0获取令牌时返回Unauthorized:授权码验证失败
问题描述
在沙箱环境中使用OAuth2.0获取新的access_token和refresh_token时,持续收到以下错误返回:
data: { status: 'Unauthorized', message: 'Failed to validate authentication code.' }
我的实现代码如下:
const oauth_request_headers = { Authorization: "Client " + client_secret, Accept: "application/json", "Content-Type": "application/json", }; const baseUrl = "https://apisandbox.dev.clover.com"; const option = { method: "POST", url: `${baseUrl}/oauth/v2/token`, headers: oauth_request_headers, // Same result with or without header as well. data: JSON.stringify({ // Same result whether or not I stringify or not. client_id: client_id, client_secret: client_secret, code: code, }), }; const cloverResponse = await axios.request(option);
请问我的操作哪里出错了?
问题分析与解决方案
你的代码存在三个核心问题,不符合Clover OAuth2 token端点的要求:
1. Authorization Header格式错误
Clover的OAuth2 token端点要求使用Basic认证,需要将client_id和client_secret用冒号拼接后进行Base64编码,格式为Basic <base64编码的client_id:client_secret>,而非你当前使用的Client + client_secret。
2. 请求体格式错误
Clover的token端点仅接受application/x-www-form-urlencoded格式的请求体,不支持application/json。你不需要将数据JSON序列化,应该以表单键值对的形式传递。
3. 缺少必填的授权类型参数
请求token时必须指定grant_type参数,对于授权码流程,该值应为authorization_code。
修正后的代码
// 生成Basic认证的header值 const authString = `${client_id}:${client_secret}`; const base64Auth = Buffer.from(authString).toString('base64'); const oauth_request_headers = { Authorization: `Basic ${base64Auth}`, Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded", }; const baseUrl = "https://apisandbox.dev.clover.com"; const option = { method: "POST", url: `${baseUrl}/oauth/v2/token`, headers: oauth_request_headers, // 使用URLSearchParams构建表单格式的请求体 data: new URLSearchParams({ grant_type: "authorization_code", code: code, }), }; const cloverResponse = await axios.request(option);
额外注意事项
- 确保
code是有效的授权码:授权码只能使用一次,且有效期较短(通常几分钟),若已使用或过期会触发验证失败。 - 确认沙箱环境的
client_id和client_secret与应用创建时获取的完全一致,避免拼写错误。
内容的提问来源于stack exchange,提问作者Aadim Chaulagain
相关产品推荐
相关产品推荐

