Overview
Better Auth adaptorである@dodopayments/better-authは、ユーザーをDodo Paymentsに接続するBetter Auth pluginです。次の機能を提供します:
- サインアップ時の顧客作成またはメールアドレスによる顧客の紐付け(任意)
- 商品slugのマッピングに対応したcheckout session(推奨されるcheckout方法)
- セルフサービスのCustomer Portal
- usage-based billing向けの使用量取り込みおよびレポート用endpoint
- signature verificationに対応したwebhook event処理
- すべてのendpoint用のTypeScript型
You need a Dodo Payments account and API keys to use this integration.
Prerequisites
- Node.js 16以降
- Dodo Payments dashboardへのアクセス
- Better Auth 1.4またはそれ以降の1.x releaseを使用する既存のproject
Installation
1
Install Dependencies
project rootで次のcommandを実行します:
Adaptor、Dodo Payments SDK、Better Auth、Zodがinstallされます。
Setup
1
Configure Environment Variables
これらのvariableを
.env fileに追加します。dashboardの Developer → API Keys でAPI keyを作成します。webhook secretは、当ページのWebhooksセクションで説明しているとおり、webhook endpointを追加したときに取得できます。BETTER_AUTH_SECRETは、32文字以上のrandom stringです。2
Set Up Server-Side Integration
src/lib/auth.tsを作成または更新します:user tableにdodoCustomerId fieldを追加し、各ユーザーのDodo Payments customer IDを保存します。pluginを追加した後、Better Auth CLIでdatabase schemaを更新します。3
Set Up Client-Side Integration
src/lib/auth-client.tsを作成または更新します:使用例
新しいintegrationには
authClient.dodopayments.checkoutSessionを使用します。
legacyのcheckout methodはdeprecatedであり、backward compatibilityのためだけに残されています。Checkout Sessionの作成(推奨)
設定済みのslugまたはproduct cartからcheckout sessionを作成し、返されたURLにcustomerをredirectします:checkoutSessionがいくつかのfieldを自動入力します:
- Billing address: checkoutがcustomerから収集するため、最初から指定する必要はありません。事前入力するには
billing_addressを渡します。 - Customer: signed-in userの場合、pluginはBetter Auth sessionのemailとnameを使用し、渡された
customerobjectを無視します。signed-in userがいない場合は、customerobjectを使用します。 - Other fields: argumentには、Create Checkout Session endpointのrequest bodyと同じfieldに加え、
slugおよびreferenceIdを指定できます。
slugもproduct_cartも渡さない場合、requestは400 errorで失敗します。
return URLはserver pluginで設定された
successUrlから取得され、
appのURLを基準に解決されます。pluginはclient payload内のreturn_urlを無視します。Legacy Checkout(Deprecated)
legacy methodにはbillingとcustomerが必要で、deprecatedなdynamic checkout flowを通じてpayment linkを作成します。customerに設定したfieldは、sessionのemailとnameより優先されます。
Customer Portalへのアクセス
portal endpointには、verified email addressを持つsigned-in userが必要です。ユーザーにDodo Payments customerがまだない場合、pluginはemailで既存のcustomerを検索するか、新しく作成します。customer.portal()はportal URLを返します:
Customer Dataの一覧表示
signed-in customerのsubscriptionとpaymentを一覧表示します。pageは1から開始し、statusで結果をfilterします:
Metered Usageの追跡
serverでusage() pluginをenableすると、usage-based billing向けのusage eventを記録し、customerが自分のusageを確認できるようになります。どちらのmethodにも、verified email addressを持つsigned-in userが必要です。
authClient.dodopayments.usage.ingestはsigned-in userのeventを記録します。authClient.dodopayments.usage.meters.listはsigned-in customerのusage eventを一覧表示します。page_number、page_size、event_name、meter_id、start、endのquery parameterを受け付けます。
meter_idを省略すると、customerのすべてのusage eventがlistに含まれます。meter_idを指定すると、そのmeterに一致するeventだけが含まれます。
Webhooks
webhooks pluginは各Dodo Payments eventのsignatureを検証し、handlerを呼び出します。デフォルトのendpointは
/api/auth/dodopayments/webhooksです。1
Generate and Set Webhook Secret
dashboardで Developer → Webhooks に移動し、endpoint URLを追加します。例:
https://<your-domain>/api/auth/dodopayments/webhooks。endpointのsigning secretを.env fileにコピーします:2
Handle Webhook Events
処理する各eventにhandlerを渡します。
onPayloadはすべてのeventに対して実行されます:{ received: true }を返します。
Supported Webhook Event Handlers
各handlerは、そのevent typeに対するverified payloadを受け取ります:Configuration Reference
Plugin Options
Plugin Options
- client (required): DodoPayments client instance
- createCustomerOnSignUp (optional): ユーザーのサインアップ時にDodo Payments customerを作成するか、同じemailの既存customerを紐付けます。ユーザーのdetailsが変更された場合、pluginはcustomerも更新します。
- use (required): enableするpluginのarray(checkout、portal、usage、webhooks)
- getCustomerParams (optional): Better Auth
Userを受け取り、Dodo Payments customerの作成および更新時に追加するfieldを返すfunction(例:metadata、phone_number)。asyncにできます。
Checkout Plugin Options
Checkout Plugin Options
- products:
{ productId, slug }objectのarray、またはそのarrayを返すasync function - successUrl: payment成功後のredirect先URL
- authenticatedUsersOnly: user authenticationを必須にするか(デフォルト:
false)
Troubleshooting & Tips
Common Issues
Common Issues
- Invalid API key:
.env内のDODO_PAYMENTS_API_KEYを確認し、keyのmodeがenvironmentと一致していることを確認します。 - Webhook signature mismatch: webhook secretがDodo Payments dashboardで設定したものと一致していることを確認します。
- Customer not created:
createCustomerOnSignUpがtrueに設定されていることを確認します。 - Portal or usage requests return 401: userのemail addressがverifiedではありません。
Best Practices
Best Practices
- すべてのsecretとkeyにenvironment variableを使用します。
live_modeに切り替える前に、test_modeでtestします。- debuggingとauditingのためにwebhook eventをlogに記録します。