コンテンツにスキップ

アプリにコマース機能を統合する

Proyecta SDK を使用して、アプリコードからカスタマーの作成、チェックアウトの開始、機能のゲーティング、サブスクリプションのキャンセルを行います。

Stripe を接続してプロダクトを作成したら、proyecta.commerce SDK リソースを使ってコマース機能をアプリに組み込みます。最もよく使う操作は次の4つです:カスタマーの作成、チェックアウトの開始、機能アクセスの確認、サブスクリプションのキャンセル。

import Proyecta from '@proyecta-ai/sdk';
const proyecta = new Proyecta({ apiKey: process.env.PROYECTA_API_KEY });

カスタマーとは、アプリ内で課金対象となるエンティティのことで、通常はユーザー、組織、またはプロジェクトを指します。対応するエンティティがデータベースに作成されたタイミングで作成し、返された id を保存しておくことで、チェックアウトやアクセス確認時にカスタマーを参照できます。

const customer = await proyecta.commerce.customers.create({
email: 'alice@example.com',
name: 'Alice Liddell',
});
await db.users.update({ id: userId, proyectaCustomerId: customer.id });

作成時または customers.update() を通じて、請求先住所(line1、line2、city、state、postal_code、country)を渡すこともできます。

commerce.checkout() は Stripe がホストするチェックアウトセッションを作成し、カスタマーをリダイレクトするための URL を返します。支払い完了後、Stripe はカスタマーを指定した success_url にリダイレクトします。

const { url } = await proyecta.commerce.checkout({
customer_id: customer.id,
line_items: [{ variant_id: 'var_pro_monthly', quantity: 1 }],
success_url: 'https://myapp.com/welcome',
cancel_url: 'https://myapp.com/pricing',
});
return Response.redirect(url);

line_items は複数指定できます。サブスクリプションの場合、quantity はシート数を表します。

プレミアム機能をカスタマーに使わせる前に、commerce.check() を呼び出してアクセス権を確認します:

const { has_access } = await proyecta.commerce.check({
customer_id: customer.id,
resource_id: 'feat_pro_features',
});
if (!has_access) {
return Response.json({ error: 'Upgrade required' }, { status: 402 });
}

これはプレミアムコンテンツをゲーティングするための推奨方法です。機能・エンタイトルメントのモデルについては、プロダクトと機能をご覧ください。

4. サブスクリプションをキャンセルする

Section titled “4. サブスクリプションをキャンセルする”
await proyecta.commerce.cancel({
customer_id: customer.id,
subscription_id: 'sub_123',
cancellation_timing: 'at_billing_period_end', // または 'immediate'
});

デフォルトでは、カスタマーは請求期間の終了まで引き続きアクセスできます。

これらのコードを手書きする必要はありません。よく使われるプロンプトの例:

  • "Create a Proyecta customer when a user signs up. Store the proyecta_customer_id on the user record."
  • "Build a /pricing page that shows my Proyecta products and starts a checkout when a button is clicked."
  • "Gate the /admin route — only allow users whose Proyecta customer has access to feat_admin."
  • "When a user clicks Cancel Subscription, call proyecta.commerce.cancel with at_billing_period_end."