🏦
Stripeで仮決済を作った話
Stripeの「仮決済(オーソリ)」フローの実装
Stripeを利用して、予約時に支払い枠を確保(仮決済)し、後から売上を確定(本決済)またはキャンセルする」フローの実装コードを暇なので見返してます。
技術スタック
Flutter(FlutterFlow)+Firebase+Cloud Run function(v1, FlutterFlow内からデプロイする機能を使ったため)
//js
const stripeModule = require("stripe");
const stripe = new stripeModule.Stripe(secretKey, {
// use correspoding api version to the document you are reading
apiVersion: "2025-06-30.basil",
});
コード
予約システムやフリマアプリなどで、「注文時に在庫や枠を確保し、後から売上を確定させる」実装が必要な場合があります。Stripeでは Payment Intents API を使い、capture_method を切り替えることで簡単に実現できます。Firebase Cloud Functions での実装例をベースに、主要な3つのステップを解説します。
支払い枠の確保 (Authorization)
- まず、顧客(Customer)の作成と、支払い枠の確保(仮決済)を行います。
- ポイント:
capture_method: 'manual'通常の決済ではデフォルトの automatic ですが、ここを manual に設定することで、即時引き落としではなく「オーソリ(枠の確保)」状態になります。
//This code should run in server side.
const customers = await stripe.customers.list({ email: email, limit: 1 });
var customer = customers.data[0];
if (!customer) {
customer = await stripe.customers.create({
email: email,
...(data.name && { name: data.name }),
});
}
// paymentIntents.create の例
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: 'jpy',
customer: customer.id,
capture_method: 'manual', // ← ここが重要
automatic_payment_methods: { enabled: true },
});
モバイルアプリ対応
- コード内にある ephemeralKeys.create は、iOS/Androidの Payment Sheet を表示するために必要な「一時的な鍵」です。これを発行してフロントエンドに渡すことで、セキュアな決済画面が実装できます。
const ephemeralKey = await stripe.ephemeralKeys.create(
{ customer: customer.id },
{ apiVersion: "2025-06-30.basil" }
);
showPaymentSheet.dart
import 'package:flutter/material.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
Future<bool> showPaymentSheet(
String clientSecret,
String customerId,
String ephemeralKey,
) async {
try {
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: clientSecret,
merchantDisplayName: 'merchant name',
customerId: customerId,
customerEphemeralKeySecret: ephemeralKey,
style: ThemeMode.light,
allowsDelayedPaymentMethods: true,
billingDetailsCollectionConfiguration: const BillingDetailsCollectionConfiguration(
name: CollectionMode.always,
email: CollectionMode.automatic,
phone: CollectionMode.automatic,
address: AddressCollectionMode.automatic,
),
),
);
await Stripe.instance.presentPaymentSheet();
return true;
} on StripeException catch (e) {
debugPrint('Stripe Error: ${e.error.localizedMessage}');
return false;
} catch (e) {
debugPrint('Unexpected Error: $e');
return false;
}
}
売上の確定 (Capture)
- サービス提供後や商品の発送タイミングなどで、確保した枠から実際に決済を実行します。
- ポイント:Firestore等に保存しておいた payment_intent_id を指定して実行します。
capture.js
// 支払いを確定(キャプチャ)する
//amount_to_captureで金額も指定出来る
const paymentIntent = await stripe.paymentIntents.capture(paymentIntentId);
// 成功後、自前DB(Firestore等)のステータスを更新
await firestore.collection('payment_intents').doc(authorizationDocId).update({
status: 'captured',
capturedAt: admin.firestore.FieldValue.serverTimestamp(),
});
仮決済のキャンセル (Cancel)
- 予約のキャンセルなどが発生した場合、確保していた枠を解放します。
- ポイント:paymentIntents.cancel確定前であれば「返金(Refund)」ではなく「取り消し(Cancel)」となり、決済手数料も発生しないケースが一般的です(カード会社の規定によります)。
cancel.js
// 仮決済を取り消す
const paymentIntent = await stripe.paymentIntents.cancel(paymentIntentId);
まとめ
もっと色んな事が出来そうでStripeの素晴らしさを実感した。あとjs久しぶりに見た。
Discussion