【问题标题】:How to Integrate Paypal Payment gateway in laravel?如何在 laravel 中集成 Paypal 支付网关?
【发布时间】:2015-12-30 07:04:45
【问题描述】:

如何在 Laravel 中集成 Paypal 支付网关? 我试过这个http://www.17educations.com/laravel/paypal-integration-in-laravel/ 但是配置有问题,请大家多多指教

【问题讨论】:

  • 您可以通过 composer 提取 paypal sdk,创建配置文件或硬编码您的凭据,一切顺利。更多信息here。我还建议您查看@delatbabel 的答案。 Omnipay 只需一个 API 即可帮助您实现与多个提供商的商户功能。

标签: laravel paypal-sandbox laravel-5.1 paypal-rest-sdk paypal


【解决方案1】:

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

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

composer create-project --prefer-dist laravel/laravel 博客

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

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

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

第 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文件

<?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 步:创建路线
在这一步中,我们需要为贝宝付款创建路线。所以打开你的 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

<?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');
    }
  }

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

php artisan serve

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

http://localhost:8000/paywithpaypal

请访问此教程链接..

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

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

【讨论】:

  • 我按照您的视频将 paypal 与 laravel 5.2 集成到我的项目中,但我收到此错误消息:传递给 PayPal\Rest\ApiContext::setConfig() 的参数 1 必须是数组类型。 .... 在这一行: $this->_api_context->setConfig($paypal_conf['settings']);
【解决方案2】:

您想通过 PayPal 实现什么目标?遇到了什么问题?

我建议避免使用 paypal SDK,而是使用 PHP 联盟的 Omnipay。见http://omnipay.thephpleague.com/https://github.com/thephpleague/omnipay-paypal

如果您下载omnipay 库,您将在各种类标题中看到一些示例。您需要实现对 purchase() 的调用,然后有一个 returnUrl 和一个 cancelUrl,在您的 returnUrl 中,您需要实现对 completePurchase() 的调用。

如果你告诉我你想要实现什么,我可以给你一些代码示例。

【讨论】:

  • 经过 15 分钟的研究,这就像泥土一样清晰。 Examples 不举例,paypall 不解释如何使用。我什至不知道我需要 Express/Pro 什么支付宝?在这种情况下,我会在 youtube 上转发,但没有关于它的视频。如果你使用它,你会得到什么?
【解决方案3】:

到目前为止,这里有一些更简单的 laravel 选项:

  1. Omnipay - 多个网关但没有订阅(很棒的文档)
  2. Payum - 订阅多个网关(文档很烂)
  3. Srmklive/Paypal - 仅限订阅的贝宝(很棒的文档 并且非常活跃)

前两个与框架无关,这意味着你可以直接使用它们,但你必须为 laravel 配置它,但如果你想为 laravel 提供简单的方法,你应该为 laravel 使用包装器。这意味着您只需要使用包装器而不是库本身。它们都有大量的包装器。

对于那些只想使用 paypal 的人来说,别无所求,Srmklive 的 paypal 包真是太棒了。

【讨论】:

    【解决方案4】:

    到目前为止,这里有一些在 Laravel 上集成 Paypal 支付网关的更简单的选项: Tutorial link

    Github Clone Paypal Gateway

    $response = $provider->doExpressCheckoutPayment($data, $token, $payer_id)
    $payment_status = $response['ACK']
    $transaction_id = $response['PAYMENTINFO_0_TRANSACTIONID']
    

    【讨论】:

      猜你喜欢
      • 2015-06-24
      • 2014-06-03
      • 2018-07-12
      • 2021-06-04
      • 2016-01-04
      • 2019-07-26
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      相关资源
      最近更新 更多