Rayavel 8でPayPal支払いゲートウェイを統合する方法.X


このブログ記事を書いている私の現在の日付で、私はPayPalダッシュボードのイメージを示しました.それは将来変わるかもしれません.PayPalは過去に多くのことを変えました.

上記のイメージは、Paypalが後ろでどのように働くかについて、我々に考えを与えます
Step 1 : PayPalアカウントを作成します.

アカウント作成のビジネスを選択します。


ステップ2:あなたのビジネスダッシュボードから開発者ダッシュボードになった.下の画像を見てください.

ステップ3:現在開発者ダッシュボードにいる

ステップ3.1:今私のアプリと資格情報をクリックして残りのAPIアプリを購入します.下記のイメージを見てください.


アプリが作成されたときPayPalも私たちの2つのSandoxアカウントを作成しました。デフォルトのアカウントを使用したい場合は


ステップ4 :サンドボックスアカウントの作成


アカウントにアクセスする


サンドボックスアカウントを作成した後、我々は2つのユーザーのメールがあります

1ビジネスメール


2個人的なメール


我々は、ビジネスメールを使用して我々のPayPalマーチャントアカウントにログインします.
個人的なメールを購入するには、注文ララヴァアプリケーションから.
下記の画像を見る

ここから、我々は電子メールパスを得ます.編集ボタンをクリックするとモーダルが開きます.... 上の画像を見ました

PayPalサンドボックスダッシュボードに行くこれは、PayPalマーチャントダッシュボードの本当の外観を与える.
www.sandbox.paypal.com


チェックインダッシュボード


チェックイン/個人的なダッシュボード

Hurray we have completed all the PayPal account procedure and sandbox Utilities. Congratulations
https://developer.paypal.com/docs/business/get-started/


Note :
When we create our  PayPal Rest Api App from the My app and Credential menu.
 By Default PayPal give us two accounts One personal,
 second business.

今すぐビジネスロジックと他の要点にジャンプできます。

  • Step 6 : ClientRoundのIDとClientRoundの秘密を
    あなたの下に私のアプリ&資格情報のメニューをクリックして
  • Step 7 :あなたのLaravelにClientRageのIDとClientCountの秘密を当てる.envファイル
  • PAYPAL_MODE=sandbox
    PAYPAL_SANDBOX_CLIENT_ID=
    PAYPAL_SANDBOX_CLIENT_SECRET=
    
    
  • Step 8 :インストールhttps://github.com/srmklive/laravel-paypal
  • composer require srmklive/paypal

    which a wrapper on PayPal SDK
    https://github.com/paypal/Checkout-PHP-SDK

  • Step 9 :私たちのsrmklive/laravel paypalの設定を公開しました
  • php artisan vendor:publish --provider "Srmklive\PayPal\Providers\PayPalServiceProvider"
    
  • Step 10 : PayPalのapp configフォルダに移動します.PHPファイルconfig/paypal.php
  • Step 11 : CapentRage ID、PayPalへの秘密を追加します.PHPファイル
  • 'mode'    => env('PAYPAL_MODE', 'sandbox'), // Can only be 'sandbox' Or 'live'. If empty or invalid, 'live' will be used.
        'sandbox' => [
            'client_id'         => env('PAYPAL_SANDBOX_CLIENT_ID'),
            'client_secret'    =>env('PAYPAL_SANDBOX_CLIENT_SECRET',),
        ],
    

  • Step 11.1 : APIのルートを作成します.PHPファイル

    we will be sending api request to our server side laravel app from our javascript paypal sdk. That's why we create route on api.php. benefit of doing these we don't need to send CSRF token to our laravel app when we make the fetch post request to our laravel server side application. In laravel api.php route don't work with session.so we will can not use the session() on this route. we can also write route on web.php file then we have to send csrf token with our post from our javascript.


  • 手順11.2 : APIのルートを作成する.PHP
  • Route::group(['prefix'=>'paypal'], function(){
        Route::post('/order/create',[\App\Http\Controllers\Front\PaypalPaymentController::class,'create']);
        Route::post('/order/capture/',[\App\Http\Controllers\Front\PaypalPaymentController::class,'capture']);
    });
    
  • Step 11.2.1 : PayPal JavaScript SDKをあなたの刃ファイル/ページに追加します.通常ユーザは支払いたい.当社の製品のサンプルチェックアウトページ.
    PayPal Javascript SDK
  • <body>
        <!-- Set up a container element for the button -->
        <div id="paypal-button-container"></div>
    
        <!-- Include the PayPal JavaScript SDK -->
        <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script>
    
        <script>
            // Render the PayPal button into #paypal-button-container
            paypal.Buttons({
     // Call your server to set up the transaction
                 createOrder: function(data, actions) {
                    return fetch('/api/paypal/order/create', {
                        method: 'POST',
                        body:JSON.stringify({
                            'course_id': "{{$course->id}}",
                            'user_id' : "{{auth()->user()->id}}",
                            'amount' : $("#paypalAmount").val(),
                        })
                    }).then(function(res) {
                        //res.json();
                        return res.json();
                    }).then(function(orderData) {
                        //console.log(orderData);
                        return orderData.id;
                    });
                },
    
                // Call your server to finalize the transaction
                onApprove: function(data, actions) {
                    return fetch('/api/paypal/order/capture' , {
                        method: 'POST',
                        body :JSON.stringify({
                            orderId : data.orderID,
                            payment_gateway_id: $("#payapalId").val(),
                            user_id: "{{ auth()->user()->id }}",
                        })
                    }).then(function(res) {
                       // console.log(res.json());
                        return res.json();
                    }).then(function(orderData) {
    
                        // Successful capture! For demo purposes:
                      //  console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
                        var transaction = orderData.purchase_units[0].payments.captures[0];
                        iziToast.success({
                            title: 'Success',
                            message: 'Payment completed',
                            position: 'topRight'
                        });
                    });
                }
    
            }).render('#paypal-button-container');
        </script>
    </body>
    
  • Step 11.2.2 : PayPal JavaCappt SDKのインポート時
    bodyタグの底にクライアントのid = testを指定します.PHP echo config (' service . PayPal . ClientRage - id ')?>
  • 
        <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script>
    
    client-id={{config('services.paypal.client_id')}}
    
  • Step 11.2 CreateOrderのJavaScript SDKで、私たちのLaraveアプリにポストリクエストを送信する/API/PayPal/Order/Create URLを書きます.
  • createOrder: function(data, actions) {
                    return fetch('/api/paypal/order/create', {
                        method: 'POST',
                        body:JSON.stringify({
                            'course_id': "{{$course->id}}",
                            'user_id' : "{{auth()->user()->id}}",
                            'amount' : $("#paypalAmount").val(),
                        })
                    }).then
    
  • Step 11.3 : PayPalPaymentControllerの作成php artisan make:controller PaypalPaymentController
  • Step 11.4 : PayPalPaymentControllerの作成方法
  • Step 11.5 :使用しているパッケージを使用してPayPalにロジックを作成しリクエストを作成する
  •   public function create(Request $request)
        {
            $data = json_decode($request->getContent(), true);
    
            $this->paypalClient->setApiCredentials(config('paypal'));
            $token = $this->paypalClient->getAccessToken();
            $this->paypalClient->setAccessToken($token);
            $order = $this->paypalClient->createOrder([
                "intent"=> "CAPTURE",
                "purchase_units"=> [
                     [
                        "amount"=> [
                            "currency_code"=> "USD",
                            "value"=> $data['amount']
                        ],
                         'description' => 'test'
                    ]
                ],
            ]);
            $mergeData = array_merge($data,['status' => TransactionStatus::PENDING, 'vendor_order_id' => $order['id']]);
            DB::beginTransaction();
            Order::create($mergeData);
            DB::commit();
            return response()->json($order);
    
    
            //return redirect($order['links'][1]['href'])->send();
           // echo('Create working');
        }
    
    コードスニペットを設定し、PayPalにアクセス要求を取得するためにPOSTリクエストを送信する
    $this->paypalClient->setApiCredentials(config('paypal'));
            $token = $this->paypalClient->getAccessToken();
            $this->paypalClient->setAccessToken($token);
    
    PayPalの上でPayPalの上で注文を作成するコードの下にid オーダーID
    $order = $this->paypalClient->createOrder([
                "intent"=> "CAPTURE",
                "purchase_units"=> [
                     [
                        "amount"=> [
                            "currency_code"=> "USD",
                            "value"=> $data['amount']
                        ],
                         'description' => 'test'
                    ]
                ],
            ]);
    
    PayPalの注文IDをデータベースに保存する
    $mergeData = array_merge($data,['status' => TransactionStatus::PENDING, 'vendor_order_id' => $order['id']]);
            DB::beginTransaction();
            Order::create($mergeData);
            DB::commit();
            return response()->json($order);
    

    注文を作成した後、PayPalの支払いモードを開きます。個人としてログインしてPayPal支払いフォームが表示されます。




    PayPalフォームモデルのPaypmentボタンをクリックすると.
    OnBelveのJavaScript PayPal SDKは、我々のLaravelアプリにPayPalから作成された注文を作成し、オーダーオーダープロセスにポストリクエストを行います.
     onApprove: function(data, actions) {
                    return fetch('/api/paypal/order/capture' , {
                        method: 'POST',
                        body :JSON.stringify({
                            orderId : data.orderID,
                            payment_gateway_id: $("#payapalId").val(),
                            user_id: "{{ auth()->user()->id }}",
                        })
                    }).
    
    ポストAPI/PayPal/順序/キャプチャは、PayPalPaymentController上で私たちの新しいメソッドを作成するためにつながるpublic function capture(Request $request)我々のビジネスロジックを書く方法
    
    public function capture(Request $request)
        {
            $data = json_decode($request->getContent(), true);
            $orderId = $data['orderId'];
            $this->paypalClient->setApiCredentials(config('paypal'));
            $token = $this->paypalClient->getAccessToken();
            $this->paypalClient->setAccessToken($token);
            $result = $this->paypalClient->capturePaymentOrder($orderId);
    
    //            $result = $result->purchase_units[0]->payments->captures[0];
            try {
                DB::beginTransaction();
                if($result['status'] === "COMPLETED"){
                    $transaction = new Transaction;
                    $transaction->vendor_payment_id = $orderId;
                    $transaction->payment_gateway_id  = $data['payment_gateway_id'];
                    $transaction->user_id   = $data['user_id'];
                    $transaction->status   = TransactionStatus::COMPLETED;
                    $transaction->save();
                    $order = Order::where('vendor_order_id', $orderId)->first();
                    $order->transaction_id = $transaction->id;
                    $order->status = TransactionStatus::COMPLETED;
                    $order->save();
                    DB::commit();
                }
            } catch (Exception $e) {
                DB::rollBack();
                dd($e);
            }
            return response()->json($result);
        }
    
    
    もう一度、我々は以下の断片を使っているアクセストークンを得るためにPayPalにポストリクエストをします
     $data = json_decode($request->getContent(), true);
            $orderId = $data['orderId'];
            $this->paypalClient->setApiCredentials(config('paypal'));
            $token = $this->paypalClient->getAccessToken();
            $this->paypalClient->setAccessToken($token);
    
    次に、CapturePaymentOrder ()を使用して支払いを行います.$result = $this->paypalClient->capturePaymentOrder($orderId);それから、我々のデータベースは、ものを保存します
     DB::beginTransaction();
                if($result['status'] === "COMPLETED"){
                    $transaction = new Transaction;
                    $transaction->vendor_payment_id = $orderId;
                    $transaction->payment_gateway_id  = $data['payment_gateway_id'];
                    $transaction->user_id   = $data['user_id'];
                    $transaction->status   = TransactionStatus::COMPLETED;
                    $transaction->save();
                    $order = Order::where('vendor_order_id', $orderId)->first();
                    $order->transaction_id = $transaction->id;
                    $order->status = TransactionStatus::COMPLETED;
                    $order->save();
                    DB::commit();
    
    ハッピーコーディング.私のポストを読んでくれてありがとう.フィードバックのコメントを残す.一角獣を与える.

    Reference
    developer.paypal.com/docs/business/checkout/set-up-standard-payments
    https://developer.paypal.com/docs/business/checkout/set-up-standard-payments/#1-add-payment-buttons
    https://github.com/paypal/Checkout-PHP-SDK#code
    https://github.com/srmklive/laravel-paypal/issues/407#issuecomment-864521831