如何在laravel中集成Paypal Payment网关? [英] How to Integrate Paypal Payment gateway in laravel?

查看:68
本文介绍了如何在laravel中集成Paypal Payment网关?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Laravel中集成Paypal Payment网关? 我尝试过 http://www.17educations.com/laravel/paypal-integration -in-laravel/ 但是配置有问题,请任何人说些想法

How to Integrate Paypal Payment gateway in Laravel? I tried this http://www.17educations.com/laravel/paypal-integration-in-laravel/ but config have some problem,Please anybody say some ideas

推荐答案

遵循以下几条步骤:
1)安装Laravel应用程序
2)数据库配置
3)安装必需的软件包
4)配置paypal.php文件
5)创建路线
6)创建控制器
7)创建视图文件

Follow Bellow Few Step:
1)Install Laravel Application
2)Database Configuration
3)Install Required Packages
4)configuration paypal.php file
5)create route
6)create controller
7)create view file

第1步:安装Laravel应用程序
我们从头开始,所以我们需要使用bellow命令获取新的Laravel应用程序,因此打开终端OR命令提示符并运行bellow命令:

Step 1 : Install Laravel Application
we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:


composer create-project --prefer-dist laravel/laravel blog

第2步:数据库配置
在此步骤中,我们需要进行数据库配置,您必须在.env文件中添加以下详细信息.
1.数据库用户名
1.数据库密码
1.数据库名称

Step 2 : Database Configuration
In this step, we require to make database configuration, you have to add
following details on your .env file.
1.Database Username
1.Database Password
1.Database Name

.env文件中还提供主机和端口详细信息,您可以像在系统中一样配置所有详细信息,因此可以像下面这样放置: .env

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow: .env

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

第3步:安装必需的软件包
我们需要以下2个软件包将palpal付款集成到我们的laravel应用程序中. 在composer.json文件中添加以下两个软件包.

Step 3 : Install Required Packages
We have required following 2 packages for integrate paypal payment in our laravel application. add following two package in your composer.json file.

"guzzlehttp/guzzle": "~5.4",
"paypal/rest-api-sdk-php": "*",

然后在终端中运行以下命令. vendor:publish命令用于从供应商软件包文件复制应用程序中的一些配置文件.

then after run following command in your terminal. vendor:publish command is used to copy few configuration file in your application from vendor package file.

php artisan vendor:publish

运行此命令后,然后在 config/paypal.php 路径中自动创建paypal.php文件.

after run this command, then after automatic create paypal.php file in your config/paypal.php path.

第4步:配置paypal.php文件

Step 4 : Configuration paypal.php file

<?php

return array(
/** set your paypal credential **/
'client_id' =>'paypal client_id',
'secret' => 'paypal secret ID',
/**
* SDK configuration 
*/
'settings' => array(
    /**
    * Available option 'sandbox' or 'live'
    */
    'mode' => 'sandbox',
    /**
    * Specify the max request time in seconds
    */
    'http.ConnectionTimeOut' => 1000,
    /**
    * Whether want to log to a file
    */
    'log.LogEnabled' => true,
    /**
    * Specify the file that want to write on
    */
    'log.FileName' => storage_path() . '/logs/paypal.log',
    /**
    * Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
    *
    * Logging is most verbose in the 'FINE' level and decreases as you
    * proceed towards ERROR
    */
    'log.LogLevel' => 'FINE'
    ),
);

第5步:创建路线
在此步骤中,我们需要为Paypal付款创建路线.因此,打开您的 routes/web.php 文件并添加以下路由. routes/web.php

Step 5: Create Route
In this is step we need to create route for paypal payment. so open your routes/web.php file and add following route. routes/web.php

Route::get('paywithpaypal', array('as' => 'addmoney.paywithpaypal','uses' => 'AddMoneyController@payWithPaypal',));
Route::post('paypal', array('as' => 'addmoney.paypal','uses' => 'AddMoneyController@postPaymentWithpaypal',));
Route::get('paypal', array('as' => 'payment.status','uses' => 'AddMoneyController@getPaymentStatus',));

第6步:创建控制器
在这一点上,现在我们应该在此路径 app/Http/Controllers/AddMoneyController.php 中将新的控制器创建为AddMoneyController.该控制器将管理布局和付款过帐请求,因此运行bellow命令以生成新的控制器:

Step 6: Create Controller
In this point, now we should create new controller as AddMoneyController in this path app/Http/Controllers/AddMoneyController.php. this controller will manage layout and payment post request, So run bellow command for generate new controller:

php artisan make:controller AddMoneyController

好吧,现在将波纹管内容放入控制器文件中:
app/Http/Controllers/AddMoneyController.php

Ok, now put bellow content in controller file:
app/Http/Controllers/AddMoneyController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;
use Input;

/** All Paypal Details class **/
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;

class AddMoneyController extends HomeController
{

    private $_api_context;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        /** setup PayPal api context **/
        $paypal_conf = \Config::get('paypal');
        $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
        $this->_api_context->setConfig($paypal_conf['settings']);
    }



    /**
     * Show the application paywith paypalpage.
     *
     * @return \Illuminate\Http\Response
     */
    public function payWithPaypal()
    {
        return view('paywithpaypal');
    }

    /**
     * Store a details of payment with paypal.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postPaymentWithpaypal(Request $request)
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $item_1 = new Item();

        $item_1->setName('Item 1') /** item name **/
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setPrice($request->get('amount')); /** unit price **/

        $item_list = new ItemList();
        $item_list->setItems(array($item_1));

        $amount = new Amount();
        $amount->setCurrency('USD')
            ->setTotal($request->get('amount'));

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Your transaction description');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('payment.status')) /** Specify return URL **/
            ->setCancelUrl(URL::route('payment.status'));

        $payment = new Payment();
        $payment->setIntent('Sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirect_urls)
            ->setTransactions(array($transaction));
            /** dd($payment->create($this->_api_context));exit; **/
        try {
            $payment->create($this->_api_context);
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            if (\Config::get('app.debug')) {
                \Session::put('error','Connection timeout');
                return Redirect::route('addmoney.paywithpaypal');
                /** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/
                /** $err_data = json_decode($ex->getData(), true); **/
                /** exit; **/
            } else {
                \Session::put('error','Some error occur, sorry for inconvenient');
                return Redirect::route('addmoney.paywithpaypal');
                /** die('Some error occur, sorry for inconvenient'); **/
            }
        }

        foreach($payment->getLinks() as $link) {
            if($link->getRel() == 'approval_url') {
                $redirect_url = $link->getHref();
                break;
            }
        }

        /** add payment ID to session **/
        Session::put('paypal_payment_id', $payment->getId());

        if(isset($redirect_url)) {
            /** redirect to paypal **/
            return Redirect::away($redirect_url);
        }

        \Session::put('error','Unknown error occurred');
        return Redirect::route('addmoney.paywithpaypal');
    }

    public function getPaymentStatus()
    {
        /** Get the payment ID before session clear **/
        $payment_id = Session::get('paypal_payment_id');
        /** clear the session payment ID **/
        Session::forget('paypal_payment_id');
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
            \Session::put('error','Payment failed');
            return Redirect::route('addmoney.paywithpaypal');
        }
        $payment = Payment::get($payment_id, $this->_api_context);
        /** PaymentExecution object includes information necessary **/
        /** to execute a PayPal account payment. **/
        /** The payer_id is added to the request query parameters **/
        /** when the user is redirected from paypal back to your site **/
        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));
        /**Execute the payment **/
        $result = $payment->execute($execution, $this->_api_context);
        /** dd($result);exit; /** DEBUG RESULT, remove it later **/
        if ($result->getState() == 'approved') { 

            /** it's all right **/
            /** Here Write your database logic like that insert record or value in database if you want **/

            \Session::put('success','Payment success');
            return Redirect::route('addmoney.paywithpaypal');
        }
        \Session::put('error','Payment failed');

        return Redirect::route('addmoney.paywithpaypal');
    }
  }

现在我们可以运行示例了,所以请运行bellow命令ro quick run:

Now we are ready to run our example so run bellow command ro quick run:

php artisan serve

现在,您可以在浏览器中打开以下网址:

Now you can open bellow URL on your browser:

http://localhost:8000/paywithpaypal

请访问此toturials链接.

please visit this toturials link..

https://www.youtube.com/watch?v=ly2xm_NM46g

http://laravelcode.com/发布/如何在Laravel-54中整合Paypal付款网关

这篇关于如何在laravel中集成Paypal Payment网关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆