React集成PayPal暂停订阅API时出现错误求助
React中PayPal暂停订阅API调用失败排查
我正在React应用里集成PayPal的暂停订阅API,但对实现细节不太清楚。我先获取了认证token,再用它调用暂停订阅的接口,已经把官方文档里的curl命令转成了axios代码,但感觉哪里用错了,现在调用失败了。
以下是我使用的代码:
async function cancel() { const response = await axios.post( 'https://api-m.sandbox.paypal.com/v1/oauth2/token', new URLSearchParams({ 'grant_type': 'client_credentials' }), { headers: { 'Accept': 'application/json', 'Accept-Language': 'en_US' }, auth: { username: 'MY CLIENT ID IS HERE', password: 'MY SECRET IS HERE' } } ); const response2 = await axios.post( 'https://api-m.sandbox.paypal.com/v1/billing/subscriptions/I-BW452GLLEP1G/suspend', '', { headers: { 'Content-Type': 'application/json', Authorization: response.data.access_token } } ); }
控制台返回如下错误:




问题修复方案
- Authorization头格式错误:PayPal的认证要求必须在token前加上
Bearer前缀,你直接传入了token字符串,导致认证失败。 - 请求体格式错误:暂停订阅的POST接口需要接收合法的JSON格式请求体,你传了空字符串,会触发400参数错误,应该传空JSON对象
{}。 - 敏感信息泄露风险:绝对不要在React前端代码里硬编码PayPal的Client ID和Secret!前端代码会被用户直接查看,敏感信息会泄露,必须把这些API调用逻辑放到你的后端服务中,前端只调用自己的后端接口。
修复后的示例代码
async function suspendSubscription() { try { // 警告:这段获取token的代码必须移到后端,禁止在前端暴露密钥! const tokenResponse = await axios.post( 'https://api-m.sandbox.paypal.com/v1/oauth2/token', new URLSearchParams({ grant_type: 'client_credentials' }), { headers: { 'Accept': 'application/json', 'Accept-Language': 'en_US' }, auth: { username: '你的Client ID', password: '你的Secret' } } ); const suspendResponse = await axios.post( 'https://api-m.sandbox.paypal.com/v1/billing/subscriptions/I-BW452GLLEP1G/suspend', {}, // 传入空JSON对象而非空字符串 { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokenResponse.data.access_token}` // 加上Bearer前缀 } } ); console.log('订阅暂停成功:', suspendResponse.data); } catch (error) { console.error('请求失败详情:', error.response?.data || error.message); } }
内容的提问来源于stack exchange,提问作者Peter Bonnebaigt
相关产品推荐
相关产品推荐

