You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Xero API获取发票时遭遇403错误,请求排查解决

Xero API调用get_invoices时403错误排查与解决

错误现象

调用XeroRuby的accounting_api.get_invoices('').invoices时返回403错误,错误详情如下:

*** XeroRuby::ApiError Exception: Error message: the server returns an error

HTTP status code: 403

Response headers: {"content-length"=>"0", "server"=>"nginx", "xero-correlation-id"=>"c605f5e5-81e7-4763-ae07-093e7cb6f949", "x-appminlimit-remaining"=>"9998", "expires"=>"Thu, 02 Feb 2023 16:45:04 GMT", "cache-control"=>"max-age=0, no-cache, no-store", "pragma"=>"no-cache", "date"=>"Thu, 02 Feb 2023 16:45:04 GMT", "connection"=>"keep-alive", "x-client-tls-ver"=>"tls1.3"}

Response body:

使用的代码片段:

require 'xero-ruby'

creds = {
  client_id: '...',
  client_secret: '...',
  grant_type: 'client_credentials'
}

xero_client = XeroRuby::ApiClient.new(credentials: creds)

@token_set = xero_client.get_client_credentials_token

byebug

@invoices = xero_client.accounting_api.get_invoices('').invoices

可能原因及解决办法

1. 未传入有效的租户ID

get_invoices('')中的空字符串不是合法的租户ID,Client Credentials模式必须指定要访问的租户ID。

解决办法:
先获取可用租户列表,再传入正确的租户ID:

# 获取租户列表
tenants = xero_client.accounting_api.get_tenants
# 取第一个租户ID(根据实际需求选择)
tenant_id = tenants.first.tenant_id
# 调用get_invoices
@invoices = xero_client.accounting_api.get_invoices(tenant_id).invoices

2. 应用缺少读取发票的权限

Client Credentials模式下,应用必须拥有accounting.transactions.read权限才能读取发票。

解决办法:

  1. 登录Xero开发者后台,找到你的应用。
  2. 进入「Permissions」页面,勾选Accounting > Transactions > Read权限。
  3. 保存设置后重新获取token。

3. 应用未关联到目标租户

即使拥有有效token,若应用未被授权访问目标租户,也会返回403。

解决办法:

  1. 登录Xero会计后台,进入「Settings > Connected Apps」。
  2. 找到你的应用,点击「Connect」将其关联到当前租户。

4. Token权限范围不足

获取token时未请求读取发票的权限,导致token没有足够的访问权限。

解决办法:
初始化ApiClient时指定所需的scope:

xero_client = XeroRuby::ApiClient.new(
  credentials: creds,
  scopes: ['accounting.transactions.read']
)

同时在byebug中检查@token_set.scope,确认包含accounting.transactions.read。

内容的提问来源于stack exchange,提问作者Jack Dawson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 10:55:22