# Square API 連携 PoC

最終更新：2026-04-29
ステータス：**骨格コード（要 API キー設定で稼働）**

## 概要

Beene業務ポータルとSquareを連携し、以下を実現する：

- **読み取り**：商品マスタ／顧客／売上／在庫を毎時 or Webhook で同期
- **書き込み**：定期請求書（Subscriptions API）／注文（Orders API）作成
- **方向**：Beene側が Square の上位にあり、ポータルからの操作で Square が更新される

## 必要なもの

1. **Square Developer アプリ**（[Developer Dashboard](https://developer.squareup.com/) で作成）
   - Application ID
   - Personal Access Token（または OAuth）
   - Webhook Signing Key
2. **環境変数**（`.env` または Cloudflare Pages の Secrets）
   ```
   SQUARE_ACCESS_TOKEN=EAAA...
   SQUARE_APPLICATION_ID=sq0idp-...
   SQUARE_WEBHOOK_SIGNATURE_KEY=...
   SQUARE_ENVIRONMENT=sandbox  # or production
   ```
3. **Node.js / Deno / Cloudflare Workers** いずれかの実行環境

## ファイル構成

```
integrations/square/
├── README.md                  本ファイル
├── client.js                  Square SDK ラッパー（共通）
├── sync_catalog.js            商品マスタ取得 → Beene products に同期
├── sync_customers.js          Square Customers → Beene customers に同期
├── sync_orders.js             Orders（売上）取得 → Beene treatment_days に同期
├── create_subscription.js     ポータルからのサブスク発行
├── webhook_handler.js         Webhook 受信（Cloudflare Pages Function 想定）
└── _data/
    └── sample_response.json   API レスポンスのサンプル（オフライン開発用）
```

## クイックスタート（Node.js, Sandbox）

```bash
# 1. SDK インストール
cd integrations/square
npm init -y
npm install square dotenv

# 2. .env ファイル作成
cp .env.example .env
# → API キーを記入

# 3. 商品マスタ取得テスト
node sync_catalog.js --dry-run

# 4. 結果確認
cat ../../data/products_from_square.json
```

## 同期戦略

### Phase 1: 一方向同期（Square → Beene）
- catalog: 1日1回 cron（夜間）
- customers: 1時間ごと
- orders: 30分ごと
- payments: 30分ごと

### Phase 2: Webhook 受信
- `inventory.count.updated`
- `order.created` / `order.updated`
- `subscription.created` / `subscription.updated`
- `customer.created` / `customer.updated`

### Phase 3: 双方向同期
- ポータルからのサブスク発行 → Square Subscriptions API
- ポータルからの顧客作成 → Square Customers API
- 売上修正 → 双方向確認

## 注意事項

1. **Sandboxで先に動作確認**してから production 切替
2. **Idempotency Key** を必ず設定（重複処理防止）
3. **レート制限**：1秒あたり10リクエストまで
4. **PIIの取り扱い**：氏名・電話・メールはログに出さない
5. **トークンローテーション**：90日に1回トークン更新

## デプロイ先候補

- **Cloudflare Pages Functions**：既存ホスティングと統合（推奨）
- **Supabase Edge Functions**：DB側ロジックと近接
- **GitHub Actions**：cron同期のみなら無料で簡易

## 関連ドキュメント

- [Square Catalog API](https://developer.squareup.com/docs/catalog-api/what-it-does)
- [Square Subscriptions API](https://developer.squareup.com/docs/subscriptions-api/overview)
- [Square Webhooks](https://developer.squareup.com/docs/webhooks/overview)
- 内部：`docs/architecture.md`
- 内部：`data/schema/products.json`
