gonpre/paypalpayment

由anouar/paypalpayment分支而来,laravel-paypalpayment是一个简单的包,帮助您使用paypal REST API SDK在L4项目中处理直接信用卡支付、存储信用卡支付和PayPal账户支付。

1.1.1 2015-07-05 13:05 UTC

This package is auto-updated.

Last update: 2024-08-28 12:33:00 UTC


README

anouar/paypalpayment

注意

如果您打算使用此包与Laravel 4一起使用,请确保包含Laravel 4版本

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

laravel-paypalpayment

Build Status

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

捐赠

如果您想支持我们:点击此处支持Laravel paypal支付包并在pledgie.com进行捐赠!

观看快速演示

安装

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

"require": {
    "gonpre/paypalpayment": "dev-master"
}

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

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

'providers' => [
    // ...

    Gonpre\PayPalPayment\PayPalPaymentServiceProvider::class,
]

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

'aliases' => [
    // ...

    'PayPalPayment'   => Gonpre\PayPalPayment\Facades\PayPalPayment::class,
]

最后,通过运行此CMDphp artisan vendor:publish发布包配置

配置

默认情况下,此包从laravel配置路径中的paypal_payment.php文件加载配置,但如果您想使用ini配置文件,请将config.ini设置中的true更改

    'config' => [
        'ini' => true,
    ],

然后转到vendor\gonpre\paypalpayment\src\Gonpre\PayPalPayment\sdk_config.ini

设置您的SDK配置acct1.ClientIdacct1.ClientSecret,将service.mode设置为所需的模式,默认设置为测试模式,即service.mode="sandbox"。如果您要上线,请将其更改为线上模式service.mode="live"

;## This is an example configuration file for the SDK.
;## The sample scripts configure the SDK dynamically
;## but you can choose to go for file based configuration
;## in simpler apps (See bootstrap.php for more).
[Account]
acct1.ClientId = AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS
acct1.ClientSecret = EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL

;Connection Information
[Http]
; Add Curl Constants to be configured
; The settings provided in configurations would override defaults
; if provided in configurations
http.CURLOPT_CONNECTTIMEOUT = 30

; Adding HTTP Headers to each request sent to PayPal APIs
;http.headers.PayPal-Partner-Attribution-Id = 123123123

;http.Proxy=http://[username:password]@hostname[:port]

;Service Configuration
[Service]
; can be set to sandbox / live
mode = sandbox

;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
; Sandbox Environments: DEBUG, INFO, WARN, ERROR
; Live Environments: INFO, WARN, ERROR
; Logging is most verbose in the 'DEBUG' level and
; decreases as you proceed towards ERROR
; DEBUG level is disabled for live, to not log sensitive information.
; If the level is set to DEBUG, it will be reduced to FINE automatically,
; with a warning message
log.LogLevel=INFO

;Validation Configuration
[validation]
; If validation is set to strict, the PayPalModel would make sure that
; there are proper accessors (Getters and Setters) for each model
; objects. Accepted value is
; 'log'     : logs the error message to logger only (default)
; 'strict'  : throws a php notice message
; 'disable' : disable the validation
validation.level=disable

;Caching Configuration
[cache]
; If Cache is enabled, it stores the access token retrieved from ClientId and Secret from the
; server into a file provided by the cache.FileName option or by using 
; the constant $CACHE_PATH value in PayPal/Cache/AuthorizationCache if the option is omitted/empty.
; If the value is set to 'true', it would try to create a file and store the information.
; For any other value, it would disable it
; Please note, this is a very good performance improvement, and we would encourage you to
; set this up properly to reduce the number of calls, to almost 50% on normal use cases
; PLEASE NOTE: You may need to provide proper write permissions to /var directory under PayPal-PHP-SDK on
; your hosting server or whichever custom directory you choose
cache.enabled=true
; When using a relative path, the cache file is created
; relative to the .php file that is the entry point
; for this request. You can also provide an absolute
; path here
cache.FileName=../auth.cache

https://gist.github.com/jaypatel512/0af613871ea499985022

示例代码

1. 初始化配置

创建新的控制器PayPalPaymentController并初始化配置

class PayPalPaymentController extends BaseController {

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

    /*
     *   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()
    {
        $this->_apiContext = PayPalPayment::ApiContext();
    }

}

如果您想使用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([$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([$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([$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 (\PayPalConnectionException $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(['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文件选择配置,请确保在此处设置此配置。

结论

希望这个包能帮到一些人 -_*