jlapp / paypalpayment

laravel-paypalpayment 是一个简单包,帮助您使用 PayPal REST API SDK,在 Laravel 4 项目中处理直接信用卡支付、存储信用卡支付和 PayPal 账户支付。

1.1.1 2015-07-05 13:05 UTC

This package is not auto-updated.

Last update: 2024-09-18 19:15:05 UTC


README

##注意:如果您打算使用此包与 Laravel 4 配合,请确保包含 Laravel 4 版本

"require": {
    "anouar/paypalpayment": "1.0"
}

laravel-paypalpayment

Build Status

laravel-paypalpayment 是一个简单包,帮助您使用 PayPal REST API SDK,在 Laravel 4/5 项目中处理直接信用卡支付、存储信用卡支付和 PayPal 账户支付。

##捐赠:如果您想支持我们: 点击这里为 github 提供支持并在 pledgie.com 捐款!

观看快速演示

安装

通过 Composer 安装此包。将以下内容添加到您的 composer.json 文件中:

"require": {
    "anouar/paypalpayment": "~1.0"
}

接下来,运行 composer update 下载它。

将服务提供者添加到 config/app.php 文件中(Laravel 4 中为 app/config/app.php),在 providers 数组内。

'providers' => array(
    // ...

    'Anouar\Paypalpayment\PaypalpaymentServiceProvider',
)

然后添加一个别名到 config/app.php 文件中(Laravel 4 中为 app/config/app.php),在 aliases 数组内。

'aliases' => array(
    // ...

    'Paypalpayment'   => 'Anouar\Paypalpayment\Facades\PaypalPayment',
)

最后,通过运行以下 CMD 命令发布包配置:php artisan vendor:publish 然后前往 vendor\anouar\paypalpayment\src\Anouar\Paypalpayment\sdk_config.ini

设置您的 SDK 配置 acct1.ClientIdacct1.ClientSecret,设置 service.EndPoint 为您想要的模式,默认设置为测试模式,即service.EndPoint="https://api.sandbox.paypal.com"。如果您要上线,请确保取消注释沙盒模式,并取消注释在线模式。

;Account credentials from developer portal
[Account]
acct1.ClientId =AVJx0RArQzkCCsWC0evZi1SsoO4gxjDkkULQBdmPNBZ4fc14AROUq-etMEY
acct1.ClientSecret =EH5F0BAxqonVnP8M4a0c6ezUHq-UT-CWfGciPNQdUlTpWPkNyuS6eDN-tpA


;Connection Information
[Http]
http.ConnectionTimeOut = 30
http.Retry = 1
;http.Proxy=http://[username:password]@hostname[:port][/path]


;Service Configuration
[Service]
service.EndPoint="https://api.sandbox.paypal.com"
; Uncomment this line for integrating with the live endpoint 
; service.EndPoint="https://api.paypal.com"


;Logging Information
[Log]

log.LogEnabled=true

# When using a relative path, the log file is created
# relative to the .php file that is the entry point
# for this request. You can also provide an absolute
# path here
log.FileName=../PayPal.log

# Logging level can be one of FINE, INFO, WARN or ERROR
# Logging is most verbose in the 'FINE' level and
# decreases as you proceed towards ERROR
log.LogLevel=FINE

如果您不想使用 ini 文件或想动态选择配置,可以使用 $apiContext->setConfig() 方法传递配置。

    /**
     * object to authenticate the call.
     * @param object $_apiContext
     */
    private $_apiContext;

    /**
     * Set the ClientId and the ClientSecret.
     * @param 
     *string $_ClientId
     *string $_ClientSecret
     */
    private $_ClientId='AVJx0RArQzkCCsWC0evZi1SsoO4gxjDkkULQBdmPNBZT4fc14AROUq-etMEY';
    private $_ClientSecret='EH5F0BAxqonVnP8M4a0c6ezUHq-UT-CWfGciPNQOdUlTpWPkNyuS6eDN-tpA';

    /*
     *   These construct set the SDK configuration dynamiclly, 
     *   If you want to pick your configuration from the sdk_config.ini file
     *   make sure to update you configuration there then grape the credentials using this code :
     *   $this->_cred= Paypalpayment::OAuthTokenCredential();
    */
    public function __construct()
    {

        // ### Api Context
        // Pass in a `ApiContext` object to authenticate 
        // the call. You can also send a unique request id 
        // (that ensures idempotency). The SDK generates
        // a request id if you do not pass one explicitly. 

        $this->_apiContext = Paypalpayment::apiContext($this->_ClientId, $this->_ClientSecret);

        // Uncomment this step if you want to use per request 
        // dynamic configuration instead of using sdk_config.ini

        $this->_apiContext->setConfig(array(
            'mode' => 'sandbox',
            'http.ConnectionTimeOut' => 30,
            'log.LogEnabled' => true,
            'log.FileName' => __DIR__.'/../PayPal.log',
            'log.LogLevel' => 'FINE'
        ));

    }

这就是全部!

示例代码

##1-初始化配置 创建新的控制器 PaypalPaymentController 并初始化配置

class PaypalPaymentController extends BaseController {

    /**
     * object to authenticate the call.
     * @param object $_apiContext
     */
    private $_apiContext;

    /**
     * Set the ClientId and the ClientSecret.
     * @param
     *string $_ClientId
     *string $_ClientSecret
     */
    private $_ClientId = 'AVJx0RArQzkCCsWC0evZi1SsoO4gxjDkkULQBdmPNBZT4fc14AROUq-etMEU';
    private $_ClientSecret='EH5F0BAxqonVnP8M4a0c6ezUHq-UT-CWfGciPNQOdUlTpWPkNyuS6eDN-tpB';

    /*
     *   These construct set the SDK configuration dynamiclly,
     *   If you want to pick your configuration from the sdk_config.ini file
     *   make sure to update you configuration there then grape the credentials using this code :
     *   $this->_cred= Paypalpayment::OAuthTokenCredential();
    */
    public function __construct()
    {

        // ### Api Context
        // Pass in a `ApiContext` object to authenticate
        // the call. You can also send a unique request id
        // (that ensures idempotency). The SDK generates
        // a request id if you do not pass one explicitly.

        $this->_apiContext = Paypalpayment::ApiContext($this->_ClientId, $this->_ClientSecret);

        // Uncomment this step if you want to use per request
        // dynamic configuration instead of using sdk_config.ini

        $this->_apiContext->setConfig(array(
            'mode' => 'sandbox',
            'service.EndPoint' => 'https://api.sandbox.paypal.com',
            'http.ConnectionTimeOut' => 30,
            'log.LogEnabled' => true,
            'log.FileName' => __DIR__.'/../PayPal.log',
            'log.LogLevel' => 'FINE'
        ));
    }
     
}

如果您想使用 Laravel 配置文件:第一步是使用 artisan vendor:publish 发布配置。这将创建配置文件 storage/paypal_payment.php(Laravel 4 中为 app/config/paypal_payment.php)。配置它,然后将上面的 setConfig() 方法调用替换为

$config = config('paypal_payment'); // Get all config items as multi dimensional array
$flatConfig = array_dot($config); // Flatten the array with dots

$this->_apiContext->setConfig($flatConfig);

##2-创建支付 将 create() 函数添加到 PaypalPaymentController 控制器

    /*
    * Display form to process payment using credit card
    */
    public function create()
    {
        return View::make('payment.order');
    }

    /*
    * Process payment using credit card
    */
    public function store()
    {
        // ### Address
        // Base Address object used as shipping or billing
        // address in a payment. [Optional]
        $addr= Paypalpayment::address();
        $addr->setLine1("3909 Witmer Road");
        $addr->setLine2("Niagara Falls");
        $addr->setCity("Niagara Falls");
        $addr->setState("NY");
        $addr->setPostalCode("14305");
        $addr->setCountryCode("US");
        $addr->setPhone("716-298-1822");

        // ### CreditCard
        $card = Paypalpayment::creditCard();
        $card->setType("visa")
            ->setNumber("4758411877817150")
            ->setExpireMonth("05")
            ->setExpireYear("2019")
            ->setCvv2("456")
            ->setFirstName("Joe")
            ->setLastName("Shopper");

        // ### FundingInstrument
        // A resource representing a Payer's funding instrument.
        // Use a Payer ID (A unique identifier of the payer generated
        // and provided by the facilitator. This is required when
        // creating or using a tokenized funding instrument)
        // and the `CreditCardDetails`
        $fi = Paypalpayment::fundingInstrument();
        $fi->setCreditCard($card);

        // ### Payer
        // A resource representing a Payer that funds a payment
        // Use the List of `FundingInstrument` and the Payment Method
        // as 'credit_card'
        $payer = Paypalpayment::payer();
        $payer->setPaymentMethod("credit_card")
            ->setFundingInstruments(array($fi));

        $item1 = Paypalpayment::item();
        $item1->setName('Ground Coffee 40 oz')
                ->setDescription('Ground Coffee 40 oz')
                ->setCurrency('USD')
                ->setQuantity(1)
                ->setTax(0.3)
                ->setPrice(7.50);

        $item2 = Paypalpayment::item();
        $item2->setName('Granola bars')
                ->setDescription('Granola Bars with Peanuts')
                ->setCurrency('USD')
                ->setQuantity(5)
                ->setTax(0.2)
                ->setPrice(2);


        $itemList = Paypalpayment::itemList();
        $itemList->setItems(array($item1,$item2));


        $details = Paypalpayment::details();
        $details->setShipping("1.2")
                ->setTax("1.3")
                //total of items prices
                ->setSubtotal("17.5");

        //Payment Amount
        $amount = Paypalpayment::amount();
        $amount->setCurrency("USD")
                // the total is $17.8 = (16 + 0.6) * 1 ( of quantity) + 1.2 ( of Shipping).
                ->setTotal("20")
                ->setDetails($details);

        // ### Transaction
        // A transaction defines the contract of a
        // payment - what is the payment for and who
        // is fulfilling it. Transaction is created with
        // a `Payee` and `Amount` types

        $transaction = Paypalpayment::transaction();
        $transaction->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription("Payment description")
            ->setInvoiceNumber(uniqid());

        // ### Payment
        // A Payment Resource; create one using
        // the above types and intent as 'sale'

        $payment = Paypalpayment::payment();

        $payment->setIntent("sale")
            ->setPayer($payer)
            ->setTransactions(array($transaction));

        try {
            // ### Create Payment
            // Create a payment by posting to the APIService
            // using a valid ApiContext
            // The return object contains the status;
            $payment->create($this->_apiContext);
        } catch (\PPConnectionException $ex) {
            return  "Exception: " . $ex->getMessage() . PHP_EOL;
            exit(1);
        }

        dd($payment);
    } 

##3-列出支付 将 index() 函数添加到 PaypalPaymentController 控制器

    /*
        Use this call to get a list of payments. 
        url:payment/
    */
    public function index()
    {
        echo "<pre>";

        $payments = Paypalpayment::getAll(array('count' => 1, 'start_index' => 0), $this->_apiContext);

        dd($payments);
    }

##4-获取支付详情 将 show() 函数添加到 PaypalPaymentController 控制器

    /*
        Use this call to get details about payments that have not completed, 
        such as payments that are created and approved, or if a payment has failed.
        url:payment/PAY-3B7201824D767003LKHZSVOA
    */

    public function show($payment_id)
    {
       $payment = Paypalpayment::getById($payment_id,$this->_apiContext);

       dd($payment);
    }

##5-执行支付 仅对 payment_method"paypal" 的支付执行

    // Get the payment Object by passing paymentId
    // payment id and payer ID was previously stored in database in
    // create() fuction , this function create payment using "paypal" method
    $paymentId = '';grape it from DB;
    $PayerID = '';grape it from DB;
    $payment = Paypalpayment::getById($paymentId, $this->_apiContext);
    
    // 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 = Paypalpayment::PaymentExecution();
    $execution->setPayerId($PayerID);
    
    //Execute the payment
    $payment->execute($execution,$this->_apiContext);

前往您的 routes.php 文件,并注册到控制器的资源路由:Route::resource('payment', 'PaypalPaymentController');

这些示例动态选择 SDK 配置。如果您想从 sdk_config.ini 文件中选择配置,请确保在此处设置此配置。

结论

希望这个包能帮助到周围的人 -_*