LoginSignup
0
1

More than 1 year has passed since last update.

laravelとstripeで決済する

Last updated at Posted at 2022-11-11

今までコピペコピぺで凌いできたので整理する

まずはプロジェクトを任意のディレクトリに作成

 composer create-project laravel/laravel stripetest "8.*" --prefer-dist

(これでできない場合、プロジェクト作成の段階でバージョンに原因があったり、使っているサーバーのPHPのバージョン、composerのパス等調べてみてください。)

続いてプロジェクト内に入ります。

cd stripetest

そしてstripeのパッケージが要ります。cashierというパッケージをインストールしましょう。

composer require laravel/cashier

ところがどっこいエラーが出ることも

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires laravel/cashier ^14.3 -> satisfiable by laravel/cashier[v14.3.0, 14.x-dev].
    - laravel/cashier[v14.3.0, ..., 14.x-dev] require illuminate/console ^9.21 -> found illuminate/console[v9.21.0, ..., 9.x-dev] but these were not loaded, likely because it conflicts with another require.

You can also try re-running composer require with an explicit version constraint, e.g. "composer require laravel/cashier:*" to figure out if any version is installable, or "composer require laravel/cashier:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

"composer require laravel/cashier:*"でインストールしてみてくださいとしれっと注意書きが。。。(ワイのような素人はエラーの一行目でパニックになるから見落としがちなんや...最後まできちんと読む勇気がいるンゴね。。。)

 composer require laravel/cashier:*

無事インストールができました。(これもできない場合、冒頭と同じようにプロジェクト作成の段階でバージョンに原因があったり、使っているサーバーのPHPのバージョン、composerのパス等調べてみてください。)

コントローラーを作成

php artisan make:controller StripePaymentsController

これでコンポーザーの出番は終了です。

続いてファイルをいじっていきましょう!

routes/web.phpを開いてルートを確認します。

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StripePaymentsController; //追加①
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::post('payment', [StripePaymentsController::class, 'payment']); //追加②

追加①で先ほど作成したコントローラーを追記します。
追加②は決済した際のルートになります。後述するのでとりあえずコピペしてください。

return view('welcome');

を決済をするためのカード番号を入力するページにします。

resources/views/welcome.blade.phpを開いてください

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>決済してみるページ</title>

    </head>
    <form action="{{ asset('payment') }}" method="POST">
         @csrf
         <script
             src="https://checkout.stripe.com/checkout.js" class="stripe-button"
             data-key="{{ env('STRIPE_KEY') }}"
             data-amount="100"
             data-name="Stripe決済デモ"
             data-label="決済をする"
             data-description="これはデモ決済です"
             data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
             data-locale="auto"
             data-currency="JPY">
         </script>
    </form>
</html>

コピペしてください。

次にストライプのキーとシークレットが必要になります。(コード内の{{ env('STRIPE_KEY') }}に入ります。)
stripeで登録をして、keyとsecretを発行してください。その後.envファイルに追加してください。

STRIPE_KEY=pk_test_51LWDuCDFuWedbIpP5BtCXOzAIrhf****************
STRIPE_SECRET=sk_test_51LWDuCDFuWedbIpPmQH5vxV8eO***************

テスト環境のカード番号は42424242...
有効期限や3桁の番号はテキトーで大丈夫です。

決済を押す前に、paymentControllerのコードを編集しましょう。

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Customer;
use Stripe\Charge;

class StripePaymentsController extends Controller
{

    public function payment(Request $request)
    {

        try{
            Stripe::setApiKey(env('STRIPE_SECRET')); //①

            //ここで顧客情報を登録②
            $customer = Customer::create(array('email' => $request->stripeEmail,
                                               'source' => $request->stripeToken
                                              )
                                         );

            dump($customer);
            dump($customer->id);
            //お支払い処理③
            $charge = Charge::create(array('customer' => $customer->id,
                                           'amount' => 100,
                                           'currency' => 'jpy'
                                          )
                                     );

            //情報が色々みられます。
            dump($charge);
            dump($charge->source->id);
            dump($charge->source->brand);
            dump($charge->source->last4);
            dump($charge->source->exp_month);
            dump($charge->source->exp_year);

            return "COMPLETE";

        }catch(Exception $e){

            return $e->getMessage();

        }

    }

}


①では先ほどenvファイルに追加シークレットを使用します。
②で顧客情報をstripe側に登録します。これだけでstripeに顧客の情報を管理してくれますので、自サーバーで重要なカード番号とか管理しなくていいんですよね。素晴らしい!

代わりに顧客のIDを返してくれます。それが$customer->idです。cus_************と返ってきますので、(レンタルビデオ店の会員番号みたいなもん)これをデータベースに登録しておけば、次回このidを使うだけで支払い処理ができます。毎回毎回カード番号を打たなくてよくなります。amazonや楽天などで毎回入力しないのと同じ理屈です。楽ですね。

では新たに作ったcustomer->idを使って支払い処理をしましょう。今回はamount で100円を指定していますが、前のカード情報入力画面で値段を設定しておけば$requestから値を指定できますので、慣れたら色々やってみてください。

最後にdumpであると便利な情報を抽出しました。これも慣れたら色々使ってみてください。

0
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
0
1