Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

xero-accounting

БесплатноБез исполняемых скриптовНе проверен

Integrate with the Xero accounting API to sync invoices, expenses, bank transactions, and contacts — and generate financial reports like P&L and balance…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Xero Accounting

Overview

Connect an application to Xero's Accounting API (https://api.xero.com/api.xro/2.0). The skill covers the OAuth 2.0 authorization-code flow with token refresh, picking the organisation (tenant), syncing invoices, payments, bank transactions and contacts, and reading P&L, balance sheet and trial balance reports. The examples use plain requests; the official SDKs (xero-python 15.x, xero-node 20.x) wrap the same endpoints.

Instructions

Step 1: Register the app and get tokens

Create an app at developer.xero.com and export its XERO_CLIENT_ID, XERO_CLIENT_SECRET and XERO_REDIRECT_URI. A web app uses the authorization-code flow with the client secret; native or single-page apps use the PKCE variant without a secret. Request only the scopes the code needs:

  • accounting.transactions for invoices, payments and bank transactions
  • accounting.contacts for contacts
  • accounting.reports.read for the report endpoints
  • accounting.settings only if you read the chart of accounts
  • offline_access to receive a refresh token

Access tokens last 30 minutes. A refresh token is single use: every refresh returns a new one, which you must store, and an unused refresh token expires after 60 days.

# xero_auth.py: OAuth 2.0 token handling for the Xero API
import base64, json, os, secrets, requests
from datetime import datetime, timedelta, timezone
from urllib.parse import urlencode

CLIENT_ID = os.environ["XERO_CLIENT_ID"]
CLIENT_SECRET = os.environ["XERO_CLIENT_SECRET"]
REDIRECT_URI = os.environ["XERO_REDIRECT_URI"]
TOKEN_FILE = ".xero_tokens.json"   # development only; use a database in production
SCOPES = "openid profile email offline_access accounting.transactions accounting.contacts accounting.reports.read"

def auth_url(state: str) -> str:
    """Keep `state` in the session and compare it on the callback."""
    return "https://login.xero.com/identity/connect/authorize?" + urlencode({
        "response_type": "code", "client_id": CLIENT_ID,
        "redirect_uri": REDIRECT_URI, "scope": SCOPES, "state": state,
    })

def _token_request(data: dict) -> dict:
    basic = base64.b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode()
    r = requests.post("https://identity.xero.com/connect/token",
                      headers={"Authorization": f"Basic {basic}"}, data=data, timeout=30)
    r.raise_for_status()
    tokens = r.json()
    tokens["expires_at"] = (datetime.now(timezone.utc) + timedelta(seconds=tokens["expires_in"])).isoformat()
    with open(TOKEN_FILE, "w") as f:
        json.dump(tokens, f)          # always persist the NEW refresh token
    return tokens

def exchange_code(code: str) -> dict:
    return _token_request({"grant_type": "authorization_code", "code": code, "redirect_uri": REDIRECT_URI})

def get_access_token() -> str:
    with open(TOKEN_FILE) as f:
        tokens = json.load(f)
    if datetime.now(timezone.utc) >= datetime.fromisoformat(tokens["expires_at"]) - timedelta(minutes=5):
        tokens = _token_request({"grant_type": "refresh_token", "refresh_token": tokens["refresh_token"]})
    return tokens["access_token"]

def get_tenant_id(access_token: str, tenant_name: str | None = None) -> str:
    r = requests.get("https://api.xero.com/connections",
                     headers={"Authorization": f"Bearer {access_token}"}, timeout=30)
    r.raise_for_status()
    orgs = r.json()
    if tenant_name:
        orgs = [o for o in orgs if o["tenantName"] == tenant_name]
    return orgs[0]["tenantId"]

Step 2: Create an API client

Every accounting call needs the Xero-Tenant-Id header. Ask for JSON explicitly, because the API answers XML by default. Retry on 429 after the number of seconds in the Retry-After header.

# xero_client.py: reusable Xero API client
import time, requests
from xero_auth import get_access_token, get_tenant_id

class XeroClient:
    BASE_URL = "https://api.xero.com/api.xro/2.0"

    def __init__(self, tenant_name: str | None = None):
        self.tenant_id = get_tenant_id(get_access_token(), tenant_name)

    def request(self, method: str, endpoint: str, params=None, json=None, since: str | None = None) -> dict:
        headers = {
            "Authorization": f"Bearer {get_access_token()}",   # refreshes when needed
            "Xero-Tenant-Id": self.tenant_id,
            "Accept": "application/json",
        }
        if since:                                              # e.g. "2026-10-01T00:00:00"
            headers["If-Modified-Since"] = since
        for _ in range(3):
            r = requests.request(method, f"{self.BASE_URL}/{endpoint}", headers=headers,
                                 params=params, json=json, timeout=60)
            if r.status_code != 429:
                break
            time.sleep(int(r.headers.get("Retry-After", "10")))
        r.raise_for_status()
        return r.json()

    def get(self, endpoint, params
Полный SKILL.md на GitHub

Установить xero-accounting в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл xero-accounting?

Integrate with the Xero accounting API to sync invoices, expenses, bank transactions, and contacts — and generate financial reports like P&L and balance sheet. Use when: connecting apps to Xero, automating bookkeeping workflows, syncing accounting data, or pulling financial reports programmatically.

Как установить скилл xero-accounting?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл xero-accounting запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить xero-accounting с