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

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

问题描述

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

解决方案

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

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

<前>composer create-project --prefer-dist laravel/laravel 博客

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

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

DB_HOST=localhostDB_DATABASE=宅基地DB_USERNAME=宅基地DB_PASSWORD=秘密

第 3 步:安装所需的软件包
我们需要以下 2 个包来在我们的 Laravel 应用程序中集成贝宝支付.在 composer.json 文件中添加以下两个包.

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

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

php artisan vendor:publish

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

第四步:配置paypal.php文件

&lt;?php返回数组(/** 设置您的贝宝凭证 **/'client_id' =>'paypal client_id','秘密' =>'paypal 秘密 ID',/*** SDK配置*/'设置' =>大批(/*** 可用选项沙盒"或实时"*/'模式' =>沙箱",/*** 以秒为单位指定最大请求时间*/'http.ConnectionTimeOut' =>1000,/*** 是否要登录到文件*/'log.LogEnabled' =>真的,/*** 指定要写入的文件*/'log.FileName' =>存储路径().'/logs/paypal.log',/*** 可用选项 'FINE'、'INFO'、'WARN' 或 'ERROR'** 日志记录在FINE"级别中最为冗长,并随着您的使用而减少* 继续错误*/'log.LogLevel' =>'美好的'),);

第 5 步:创建路线
在这一步中,我们需要为贝宝支付创建路由.所以打开你的 routes/web.php 文件并添加以下路由.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.此控制器将管理布局和付款后请求,因此运行以下命令以生成新控制器:

php artisan make:controller AddMoneyController

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

_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));$this->_api_context->setConfig($paypal_conf['settings']);}/*** 显示应用程序 paywith paypalpage.** @return IlluminateHttpResponse*/公共函数 payWithPaypal(){返回视图('paywithpaypal');}/*** 使用贝宝存储付款的详细信息.** @param IlluminateHttpRequest $request* @return IlluminateHttpResponse*/公共功能 postPaymentWithpaypal(Request $request){$payer = new Payer();$payer->setPaymentMethod('paypal');$item_1 = 新项目();$item_1->setName('Item 1')/** 物品名称 **/->setCurrency('USD')->setQuantity(1)->setPrice($request->get('amount'));/** 单价 **/$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('您的交易描述');$redirect_urls = new RedirectUrls();$redirect_urls->setReturnUrl(URL::route('payment.status'))/** 指定返回 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;**/尝试 {$payment->create($this->_api_context);} catch (PayPalExceptionPPConnectionException $ex) {如果 (Config::get('app.debug')) {Session::put('error','连接超时');return Redirect::route('addmoney.paywithpaypal');/** 回声异常:".$ex->getMessage() .PHP_EOL;**//** $err_data = json_decode($ex->getData(), true);**//** 出口;**/} 别的 {Session::put('error','出现错误,不便敬请谅解');return Redirect::route('addmoney.paywithpaypal');/** die('出现错误,不便敬请谅解');**/}}foreach($payment->getLinks() as $link) {if($link->getRel() == 'approval_url') {$redirect_url = $link->getHref();休息;}}/** 添加支付 ID 到会话 **/Session::put('paypal_payment_id', $payment->getId());如果(isset($redirect_url)){/** 重定向到贝宝 **/返回重定向::离开($redirect_url);}Session::put('error','发生未知错误');return Redirect::route('addmoney.paywithpaypal');}公共函数 getPaymentStatus(){/** 在会话清除前获取付款 ID **/$payment_id = Session::get('paypal_payment_id');/** 清除会话支付ID **/会话::忘记('paypal_payment_id');if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {Session::put('error','付款失败');return Redirect::route('addmoney.paywithpaypal');}$payment = Payment::get($payment_id, $this->_api_context);/** PaymentExecution 对象包括必要的信息 **//** 执行 PayPal 帐户付款.**//** 请求查询参数中添加payer_id **//** 当用户从贝宝重定向回您的网站时 **/$execution = new PaymentExecution();$execution->setPayerId(Input::get('PayerID'));/**执行付款**/$result = $payment->execute($execution, $this->_api_context);/** dd($result);exit;/** 调试结果,稍后删除 **/if ($result->getState() == 'approved') {/** 没关系 **//** 如果需要,请在此处编写数据库逻辑,例如在数据库中插入记录或值 **/Session::put('success','付款成功');return Redirect::route('addmoney.paywithpaypal');}Session::put('error','付款失败');return Redirect::route('addmoney.paywithpaypal');}}

现在我们已经准备好运行我们的例子,所以运行下面的命令 ro quick run:

php artisan serve

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

http://localhost:8000/paywithpaypal

请访问此toturials链接..

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

http://laravelcode.com/post/how-to-integrate-paypal-payment-gateway-in-laravel-54

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

解决方案

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

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

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

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

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": "*",

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

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

Step 4 : Configuration paypal.php file

&lt;?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'
    ),
);

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',));

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

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

<?php

namespace AppHttpControllers;

use AppHttpRequests;
use IlluminateHttpRequest;
use Validator;
use URL;
use Session;
use Redirect;
use Input;

/** All Paypal Details class **/
use PayPalRestApiContext;
use PayPalAuthOAuthTokenCredential;
use PayPalApiAmount;
use PayPalApiDetails;
use PayPalApiItem;
use PayPalApiItemList;
use PayPalApiPayer;
use PayPalApiPayment;
use PayPalApiRedirectUrls;
use PayPalApiExecutePayment;
use PayPalApiPaymentExecution;
use PayPalApiTransaction;

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 IlluminateHttpResponse
     */
    public function payWithPaypal()
    {
        return view('paywithpaypal');
    }

    /**
     * Store a details of payment with paypal.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    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 (PayPalExceptionPPConnectionException $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');
    }
  }

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

please visit this toturials link..

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

http://laravelcode.com/post/how-to-integrate-paypal-payment-gateway-in-laravel-54

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

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