2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel × Stripeで決済機能をサクッと実装する方法【カード・コンビニ対応】

Posted at

LaravelでECサイトを作成した際に「決済機能どうしよう?」となった方、多いのではないでしょうか?
この記事では、Stripeのカード支払いとコンビニ支払いの両方に対応した決済機能の導入方法をステップ形式で解説します。

対象読者

・LaravelでECサイトを作成している人

・Stripeの実装方法を一通り学びたい人

・Webhookなどの非同期処理に触れてみたい人

準備

・Stripeアカウントの作成・APIキー取得
Stripeの公式サイトでアカウントを作成し、ダッシュボード > 開発者 > APIキーから以下を取得します。

公開可能キー(Publishable key)
シークレットキー(Secret key)

.envに追記:

STRIPE_PUBLIC_KEY=pk_test_************
STRIPE_SECRET_KEY=sk_test_************

Laravel 側の実装

・Stripe PHP SDKをインストール

composer require stripe/stripe-php

コントローラーの作成

use Stripe\StripeClient;

public function purchase(Request $request)
{
    $stripe = new StripeClient(config('stripe.secret'));

    $checkout = $stripe->checkout->sessions->create([
        'payment_method_types' => ['card', 'konbini'],
        'line_items' => [[
            'price_data' => [
                'currency' => 'jpy',
                'unit_amount' => 2000,
                'product_data' => [
                    'name' => '商品名',
                ],
            ],
            'quantity' => 1,
        ]],
        'mode' => 'payment',
        'success_url' => route('purchase.success'),
        'cancel_url' => route('purchase.cancel'),
    ]);

    return redirect($checkout->url);
}

Webhook設定(購入完了時の処理)

StripeダッシュボードでWebhook URLを登録

登録するエンドポイント例:

https://yourdomain.com/api/stripe/webhook

LaravelでWebhookのルートを追加

Route::post('/stripe/webhook', [StripeWebhookController::class, 'handle']);

Webhookコントローラーの作成

use Illuminate\Http\Request;

public function handle(Request $request)
{
    $payload = $request->getContent();
    $event = json_decode($payload, true);

    if ($event['type'] === 'checkout.session.completed') {
        $session = $event['data']['object'];

        // `購入完了処理` ここに商品購入後のロジックを追加
    }

    return response()->json(['status' => 'ok']);
}

ビュー側の対応

購入ボタンの追加

<form action="{{ route('purchase') }}" method="POST">
    @csrf
    <button type="submit">購入する(Stripeへ)</button>
</form>

注意点

・line_items.price_data.unit_amount は円ではなく「最小通貨単位」(=円なら×100)で指定。
・Webhookには署名検証も推奨されます(本番環境では必須です)。

まとめ

・Stripeのカード&コンビニ支払いに対応する方法を紹介しました。
・LaravelではStripeのライブラリを使えば比較的スムーズに実装できます。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?