使用Google Apps Script调用PayPal认证API为何认证持续失败?
解决PayPal OAuth2 Token请求的invalid_client错误
问题根源分析
你的代码存在两个核心问题,导致PayPal返回invalid_client错误:
Basic认证编码格式错误
PayPal要求Basic认证的Base64编码内容是client_id:client_secret的直接拼接,而你的代码错误地给client_id和secret加上了尖括号<>,导致编码后的凭证无效。请求体格式错误
Google Apps Script的UrlFetchApp在传递body为对象时,会默认以JSON格式发送,但PayPal的OAuth2 token接口要求使用application/x-www-form-urlencoded格式的字符串,而非JSON。
修正后的代码
function retrieveInfo() { try { const scriptProperties = PropertiesService.getScriptProperties(); const clientId = scriptProperties.getProperty('CLIENT_ID'); const secret = scriptProperties.getProperty('SECRET'); // 移除多余的尖括号,直接拼接clientId和secret const credentials = `${clientId}:${secret}`; return Utilities.base64Encode(credentials, Utilities.Charset.UTF_8); } catch (err) { console.log('Failed with error %s', err.message); } } function bearerToken() { const clientInfo = retrieveInfo(); if (!clientInfo) { console.log('Failed to retrieve credentials'); return; } // 将请求体转换为x-www-form-urlencoded格式的字符串 const formBody = [ 'grant_type=client_credentials', 'ignoreCache=true', 'return_authn_schemes=true', 'return_client_metadata=true', 'return_unconsented_scopes=true' ].join('&'); const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': `Basic ${clientInfo}`, }, body: formBody, // 使用表单字符串而非对象 muteHttpExceptions: true }; const response = UrlFetchApp.fetch("https://sandbox.paypal.com/v1/oauth2/token", requestOptions); console.log(response.toString()); console.log(response.getResponseCode()); }
关键修正点说明
- 认证凭证修复:去掉了
retrieveInfo中包裹client_id和secret的尖括号,确保Base64编码的内容符合PayPal的要求。 - 请求体格式修复:将原本的对象形式的body替换为用
&连接的键值对字符串,确保请求内容以application/x-www-form-urlencoded格式发送,和Postman中的请求保持一致。 - 增加空值检查:在
bearerToken中添加了对clientInfo的空值判断,避免因凭证获取失败导致后续请求出错。
内容的提问来源于stack exchange,提问作者Joe Brigantino
相关产品推荐
相关产品推荐

