Skip to content

MMHK/xero-cli

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

29 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Xero CLI

Go Version License Release

Xero Accounting API 的命令行工具,使用 OAuth2 PKCE 流程進行認證。

功能特性

  • ✅ OAuth2 PKCE 認證流程(適合 CLI/桌面應用)
  • Config 配置管理系統(獨立的 config 命令)
  • ✅ 支援 Refresh Token 離線訪問(60 天)
  • ✅ AES-256-GCM 加密儲存 Token 和 Config(機器綁定)
  • ✅ 扁平化專案結構,易於理解和維護
  • ✅ 多種查詢功能:發票、聯絡人、帳戶、付款、貸項通知單
  • ✅ 可作為 AI Agent Skill 整合到自動化流程

快速開始

安裝方式

方法一:下載預編譯 Binary(推薦)

GitHub Releases 下載適合您系統的版本:

平台 架構 下載
Windows x86_64 (amd64) xero-cli_Windows_x86_64.zip
Windows arm64 xero-cli_Windows_arm64.zip
macOS x86_64 (Intel) xero-cli_Darwin_x86_64.tar.gz
macOS arm64 (M1/M2/M3) xero-cli_Darwin_arm64.tar.gz
Linux x86_64 (amd64) xero-cli_Linux_x86_64.tar.gz
Linux arm64 xero-cli_Linux_arm64.tar.gz

安裝步驟:

# macOS/Linux
tar -xzf xero-cli_<OS>_<ARCH>.tar.gz
chmod +x xero-cli
sudo mv xero-cli /usr/local/bin/

# Windows (PowerShell)
Expand-Archive xero-cli_Windows_x86_64.zip -DestinationPath C:\Program Files\xero-cli
# 將 C:\Program Files\xero-cli 加入 PATH

驗證安裝:

# 檢查校驗和
sha256sum -c checksums.txt

# 檢查版本
./xero-cli --version
./xero-cli -V

方法二:從原始碼編譯

git clone https://github.com/MMHK/xero-cli.git
cd xero-cli
go build -o xero-cli.exe

2. 設定

方法一:使用 Config 命令(推薦)

# 初始化配置(交互式)
xero-cli config --init

# 查看配置
xero-cli config

# 更新配置
xero-cli config --update

# 重置配置
xero-cli config --reset

配置儲存位置

  • Windows: C:\Users\<user>\AppData\Roaming\xero-cli\config.json
  • macOS: /Users/<user>/Library/Application Support/xero-cli/config.json
  • Linux: /home/<user>/.config/xero-cli/config.json

安全特性

  • AES-256-GCM 加密儲存
  • 機器綁定(防止跨機器使用)
  • 文件權限 0600(僅所有者可讀寫)

方法二:使用 .env 文件

建立 .env 檔案:

XERO_CLIENT_ID=your_client_id_here
XERO_CLIENT_SECRET=your_client_secret_here  # PKCE 可選,一般 OAuth 必需
XERO_REDIRECT_URI=http://localhost:3456/callback
XERO_SCOPES=openid profile email accounting.transactions accounting.settings offline_access

預設 Scopes

openid profile email accounting.transactions accounting.settings accounting.contacts offline_access

配置來源優先級

  1. CLI flags (--client-id, --secret, ...) - 最高優先級
  2. 環境變數 (.env) - 中優先級
  3. 加密 config.json - 低優先級
  4. 預設值 - 最低優先級

3. 使用

# 認證(使用保存的配置)
./xero-cli auth

# 強制重新認證
./xero-cli auth --force

# 切換 Tenant/Organization
./xero-cli auth --switch

# 檢查狀態
./xero-cli status

# 查詢發票
./xero-cli invoices list --type ACCREC --status AUTHORISED

# 查詢聯絡人
./xero-cli contacts list --type customer

# 搜尋發票(使用 SearchTerm)
./xero-cli invoices list --search-term "INV-2024"

# 搜尋聯絡人(使用 SearchTerm)
./xero-cli contacts list --search-term "Smith"

# 查詢貸項通知單
./xero-cli creditnotes list --type ACCREC --status AUTHORISED

# 查詢剩餘可沖銷金額 > 0 的貸項通知單
./xero-cli creditnotes list --where "RemainingCredit>0"

# JSON 輸出
./xero-cli invoices list --json

# 詳細模式
./xero-cli status -v

命令參考

命令 用途 範例
auth 啟動認證 xero-cli auth
auth --force 強制重新認證 xero-cli auth --force
auth --switch 切換 Tenant xero-cli auth --switch
config 配置管理 xero-cli config
config --init 初始化配置 xero-cli config --init
config --update 更新配置 xero-cli config --update
config --reset 重置配置 xero-cli config --reset
status 檢查狀態 xero-cli status
refresh 刷新 Token xero-cli refresh
revoke 撤銷授權 xero-cli revoke
connections 列出組織 xero-cli connections
invoices list 發票列表 xero-cli invoices list --type ACCREC
invoices get 單一發票 xero-cli invoices get <uuid>
contacts list 聯絡人列表 xero-cli contacts list --type customer
contacts get 單一聯絡人 xero-cli contacts get <uuid>
accounts list 科目列表 xero-cli accounts list --type BANK
accounts get 單一科目 xero-cli accounts get <code>
payments list 付款列表 xero-cli payments list --type AR
payments get 單一付款 xero-cli payments get <uuid>
creditnotes list 貸項通知單列表 xero-cli creditnotes list --type ACCREC
creditnotes get 單一貸項通知單 xero-cli creditnotes get <uuid>

通用篩選參數

參數 說明 預設 範圍
--page 頁碼 1 1-N
--page-size 每頁數量 50 1-100
--order-by 排序欄位 varies 任意欄位名稱
--sort-direction 排序方向 varies ASC/DESC
--where WHERE 條件 - Xero 語法
--search-term 搜尋關鍵字 - 文字搜尋
--json JSON 輸出 false -

SearchTerm 搜尋功能

--search-term 參數提供快速文字搜尋功能,適用於以下場景:

Invoices(發票搜尋)

# 搜尋發票號碼或參考號
xero-cli invoices list --search-term "INV-2024"

# 搜尋參考號包含 "REF123" 的應收發票
xero-cli invoices list --search-term "REF123" --type ACCREC

# 結合其他篩選條件
xero-cli invoices list --search-term "INV" --status AUTHORISED --page-size 20

搜尋範圍:InvoiceNumber, Reference(不區分大小寫)

Contacts(聯絡人搜尋)

# 搜尋聯絡人名稱、郵件等
xero-cli contacts list --search-term "Smith"

# 搜尋客戶且名稱包含 "john"
xero-cli contacts list --search-term "john" --type customer

# 結合排序
xero-cli contacts list --search-term "ABC" --order-by Name --sort-direction ASC

搜尋範圍:Name, FirstName, LastName, ContactNumber, CompanyNumber, EmailAddress(不區分大小寫)

與 WHERE 的差異

  • --search-term:快速全文搜尋,Xero API 內部優化,效能佳
  • --where:靈活的條件組合,支持複雜邏輯運算

建議優先使用 --search-term 進行簡單文字搜尋,複雜條件再使用 --where

Order By 範例

# 依日期倒序(預設)
xero-cli invoices list --order-by Date --sort-direction DESC

# 依金額倒序(大額在前)
xero-cli invoices list --order-by Total --sort-direction DESC

# 依名稱正序(A-Z)
xero-cli contacts list --order-by Name --sort-direction ASC

# 依聯絡人名稱排序
xero-cli invoices list --order-by Contact.Name --sort-direction ASC

# 依剩餘可沖銷金額排序(貸項通知單)
xero-cli creditnotes list --order-by RemainingCredit --sort-direction DESC

# 結合 SearchTerm 搜尋
xero-cli invoices list --search-term "INV" --order-by Date --sort-direction DESC
xero-cli contacts list --search-term "ABC" --order-by Name --sort-direction ASC

Xero API 優化排序欄位

  • Invoices: InvoiceId, UpdatedDateUTC, Date(預設:UpdatedDateUTC ASC, InvoiceId ASC)
  • Contacts: UpdatedDateUTC, ContactId(預設:UpdatedDateUTC ASC, ContactId ASC)
  • Accounts: Code(預設:Code ASC)
  • Payments: UpdatedDateUTC, Date, PaymentId(預設:UpdatedDateUTC ASC, PaymentId ASC)
  • CreditNotes: UpdatedDateUTC, CreditNoteId(預設:UpdatedDateUTC ASC, CreditNoteId ASC)

WHERE 查詢範例

# 未結清應收發票
--where "Type=='ACCREC'&&AmountDue>0"

# 逾期發票
--where "DueDate<DateTime.Today&&AmountDue>0"

# 日期範圍
--where "Date>=DateTime(2024, 01, 01) AND Date<DateTime(2024, 02, 01)"

# 指定客戶
--where "Contact.ContactID=Guid('uuid-here')"

# 金額範圍
--where "AmountDue>=5000 AND AmountDue<6000"

# 貸項通知單查詢
# 剩餘可沖銷金額 > 0
--where "RemainingCredit>0"

# 已授權的應收貸項通知單
--where "Type=='ACCREC' && Status=='AUTHORISED'"

# 依金額排序
--order-by Total --sort-direction DESC

# 文字字段部分匹配(Contacts)
# 名稱包含 "MOTOR"
--where "Name.Contains('MOTOR')"

# 名稱以 "ABC" 開頭
--where "Name.StartsWith('ABC')"

# 名稱以 "LIMITED" 結尾
--where "Name.EndsWith('LIMITED')"

# 郵箱包含 "gmail"
--where "EmailAddress.Contains('gmail')"

# 統一編號包含 "123"
--where "TaxNumber.Contains('123')"

# 地址包含 "Road"
--where "AddressLine1.Contains('Road')"

# 城市包含 "Taipei"
--where "City.Contains('Taipei')"

# 聯絡人編號包含 "CUST"
--where "AccountNumber.Contains('CUST')"

# 組合查詢:客戶且名稱包含 "LIMITED"
--where "IsCustomer==true && Name.Contains('LIMITED')"

# 文字字段部分匹配(Invoices)
# 參考號包含 "INV"
--where "Reference.Contains('INV')"

# 發票號以 "2024" 開頭
--where "InvoiceNumber.StartsWith('2024')"

# 文字字段部分匹配(Accounts)
# 科目名稱包含 "Bank"
--where "Name.Contains('Bank')"

# 科目代碼以 "1" 開頭
--where "Code.StartsWith('1')"

# 文字字段部分匹配(Payments)
# 付款參考號包含 "PAY"
--where "Reference.Contains('PAY')"

# 文字字段部分匹配(CreditNotes)
# 參考號包含 "CN"
--where "Reference.Contains('CN')"

# 貸項單號以 "2024" 開頭
--where "CreditNoteNumber.StartsWith('2024')"

# SearchTerm vs WHERE 使用建議
# 簡單文字搜尋(推薦使用 searchTerm,效能更佳)
xero-cli invoices list --search-term "INV-2024"
xero-cli contacts list --search-term "Smith"

# 複雜條件組合(使用 where)
xero-cli invoices list --search-term "INV" --where "AmountDue>0"

測試

詳細測試文檔請參閱 測試指南

# 運行所有測試
go test ./...

# 詳細輸出
go test ./... -v

# 覆蓋率報告
go test ./... -cover

# 單一測試
go test -run ^TestGetPayment_Mock$ ./...
go test -run ^TestBuildOrderClause$ ./...
go test -run ^TestBuildCreditNoteWhereClause$ ./...

測試涵蓋範圍:70+ 測試用例(API 測試、WHERE Clause 測試、排序測試、認證測試)

查看完整測試指南 →

代碼質量檢查

go fmt ./...     # 格式化
go vet ./...     # 靜態分析
go build -o xero-cli.exe  # 編譯

測試檔案api_payments_test.go, api_creditnotes_test.go, cmd_helpers_test.go, api_test.go, auth_test.go, config_test.go

查看完整測試指南 →

專案結構

.
├── main.go              # 程式入口
├── types.go             # 資料結構定義
├── auth.go              # OAuth2 PKCE 認證邏輯
├── api.go               # Xero API 呼叫封裝
├── api_*.go             # 各類 API 查詢實作
├── config.go            # 設定與環境變數 + Config 管理
├── config_action.go     # Config action 實現
├── cmd.go               # CLI 命令定義
├── cmd_helpers.go       # 命令輔助函數
├── crypto.go            # 加密工具
├── utils.go             # 工具函數
├── go.mod
├── README.md            # 主說明文件
├── AGENTS.md            # AI 開發指導原則
├── .env.example         # 環境變數範本
└── docs/                # 文檔目錄
    ├── README.md        # 開發指南索引
    ├── api/             # API 端點文檔
    │   ├── invoices.md
    │   ├── contacts.md
    │   ├── payments.md
    │   ├── accounts.md
    │   └── credit-notes.md
    └── guides/          # 實現指南
        ├── oauth2-pkce.md
        ├── error-handling.md
        ├── config-system.md
        ├── testing.md
        ├── ai-agent-integration.md
        └── business-scenarios.md

開發命令

# 編譯
go build -o xero-cli.exe

# 執行
go run main.go

# 格式化
go fmt ./...

# Lint
golint ./...

# 靜態分析
go vet ./...

# 測試
go test ./...
go test -run ^TestName$ ./...
go test -cover ./...

OAuth2 PKCE 流程

1. 生成 code_verifier (43-128 字元)
2. 計算 code_challenge = SHA256(verifier)
3. 開啟瀏覽器到授權網址
4. localhost:3456 監聽回調接收 auth_code
5. 用 auth_code + code_verifier 交換 token
6. 取得 access_token (30 分鐘) + refresh_token (60 天)
7. 使用 access_token 呼叫 API

授權網址:

https://login.xero.com/identity/connect/authorize?
  response_type=code&
  client_id=YOUR_CLIENT_ID&
  redirect_uri=http://localhost:3456/callback&
  scope=openid%20profile%20email%20accounting.transactions%20offline_access&
  state=random_state&
  code_challenge=CHALLENGE&
  code_challenge_method=S256

Token 端點:

POST https://identity.xero.com/connect/token

Token 管理

Token 類型 過期時間
Access Token 30 分鐘
Refresh Token 60 天

儲存路徑:

  • Windows: C:\Users\<user>\AppData\Roaming\xero-cli\tokens.json
  • macOS: /Users/<user>/Library/Application Support/xero-cli/tokens.json
  • Linux: /home/<user>/.config/xero-cli/tokens.json

Config 儲存路徑:

  • Windows: C:\Users\<user>\AppData\Roaming\xero-cli\config.json
  • macOS: /Users/<user>/Library/Application Support/xero-cli/config.json
  • Linux: /home/<user>/.config/xero-cli/config.json

加密方式: AES-256-GCM 加密,使用機器特徵生成密鑰(綁定當前機器)

安全特性:

  • AES-256-GCM Authenticated Encryption
  • scrypt KDF 密鑰派生 (N=32768, r=8, p=1)
  • 機器綁定(machineid.ID())
  • 平台驗證(防止跨機器使用)
  • 文件權限 0600(僅所有者可讀寫)

常用 Scopes

Scope 說明
openid profile email OpenID Connect 用戶資訊
accounting.transactions 讀取發票、帳單、付款、貸項通知單等交易資料
accounting.settings 讀取組織設定、科目表等基本設定資訊
accounting.contacts 讀取客戶、供應商聯絡人資訊
offline_access 必需 取得 Refresh Token 以支持離線訪問

安全注意事項

  1. 勿提交機密資訊: .envconfig.jsontoken 檔案必須加入 .gitignore
  2. 加密儲存: Token 和 Config 使用 AES-256-GCM 加密,綁定當前機器
  3. 檔案權限: Token 和 Config 檔案使用 0600 權限(僅所有者可讀寫)
  4. 定期撤銷: 不再使用時執行 ./xero-cli revoke
  5. 最小權限: 只申請必要的 scopes
  6. 機器綁定: Config 和 Token 無法在不同機器間遷移(安全特性)
  7. 密碼模式輸入: Client Secret 使用隱藏輸入(不回顯)

API 基礎

Base URL:

https://api.xero.com/api.xro/2.0/

Headers:

Authorization: Bearer <access_token>
Xero-tenant-id: <tenant_id>
Accept: application/json

Rate Limits:

  • 每分鐘:60 次
  • 每小時:3600 次
  • 每日:50000 次

錯誤處理

錯誤 原因 解決方法
Not authenticated 未執行 auth 命令 執行 xero-cli auth
Token expired Access token 已過期 執行 xero-cli refresh
No connections found 無連接的組織 檢查 Xero 組織設定
Rate limit exceeded 超過 API 限制 等待後重試

AI Agent Skill 整合

Xero CLI 可作為 AI Agent(opencode、Cline、Cursor 等)的 CLI Skill。

快速範例

# AI 查詢發票
xero-cli invoices list --type ACCREC --status AUTHORISED --json

# AI 查詢客戶
xero-cli contacts list --type customer --json

查看完整 AI Agent 整合指南 →

業務場景範例

完整的業務場景範例(財務報表、往來對象查詢、進階查詢、jq 整合、貸項通知單應用)請參閱:

查看業務場景範例 →

快速範例

# 逾期發票查詢
xero-cli invoices list --where "Type==\"ACCREC\" && AmountDue>0 && DueDate<DateTime.Today"

# 本月收款總額
xero-cli payments list --type AR --date-from 2024-02-01 --date-to 2024-02-29 --json | jq '[.[].Amount] | add'

# 貸項通知單(剩餘可沖銷金額>0)
xero-cli creditnotes list --where "RemainingCredit>0" --order-by RemainingCredit --sort-direction DESC

自動打包與 Release

本專案使用 GoReleaser 和 GitHub Actions 實現自動化多平台打包。

支援的平台

平台 架構 檔案格式
Windows x86_64, arm64 .zip
macOS x86_64 (Intel), arm64 (M1/M2/M3) .tar.gz
Linux x86_64, arm64 .tar.gz

建立 Release

# 1. 建立語義化版本標籤
git tag v1.0.0

# 2. Push 標籤到 GitHub(自動觸發打包)
git push origin v1.0.0

# 3. 前往 GitHub Actions 查看進度
# https://github.com/MMHK/xero-cli/actions

本地測試編譯

# 安裝 GoReleaser
go install github.com/goreleaser/goreleaser/v2@latest

# 測試編譯(不建立 release)
goreleaser build --snapshot --clean

# 或使用提供的腳本
./scripts/build-release.sh        # macOS/Linux
.\scripts\build-release.bat       # Windows

配置檔案

  • .goreleaser.yaml - GoReleaser 配置
  • .github/workflows/release.yml - GitHub Actions 配置

編譯產出

每次 release 會自動生成:

  • 6 個平台的 binary(Windows/macOS/Linux × amd64/arm64)
  • checksums.txt - SHA256 校驗和
  • 自動生成的 CHANGELOG

Release 前檢查清單

  • 所有測試通過:go test ./...
  • 代碼格式化:go fmt ./...
  • 靜態分析:go vet ./...
  • 本地測試編譯:goreleaser build --snapshot

開發階段

  • 第一階段:核心認證功能
  • 第二階段:API 查詢功能
  • 第三階段:CLI 命令整合
  • 第四階段:測試與文件

相關資源

授權

MIT License

About

Xero Accounting API 的命令行工具,使用 OAuth2 PKCE 流程進行認證。 LLM agent tools

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors