Yii2贝宝支付集成

时间:2019-05-10 10:44:31

标签: php paypal yii2 yii2-advanced-app

我正在将此https://www.yiiframework.com/extension/bitcko/yii2-bitcko-paypal-api#usage与yii2配合使用以启用付款,我的代码如下所示。

public function actionMakePayment(){
          if(!Yii::$app->user->getIsGuest()){
               // Setup order information array
              $params = [
                  'order'=>[
                      'description'=>'Payment description',
                      'subtotal'=>45,
                      'shippingCost'=>0,
                      'total'=>45,
                      'currency'=>'USD',
                  ]
              ];
            // In case of payment success this will return the payment object that contains all information about the order
            // In case of failure it will return Null

            Yii::$app->PayPalRestApi->processPayment($params);
        }else{
          Yii::$app->response->redirect(Url::to(['site/signup'], true));
        }

一切都按我的预期进行,此电话将类似的东西返回给dom。

{ "id": "PAYID-LTKUAVA8WK14445NN137182H", "intent": "sale", "state": "approved", "cart": "9RE74926AX5730813", "payer": { "payment_method": "paypal", "status": "UNVERIFIED", "payer_info": { "first_name": "Susi", "last_name": "Flo", "payer_id": "KWPDGYRP2KCK4", "shipping_address": { "recipient_name": "Susi Flo", "line1": "Suso", "line2": "bldg", "city": "Spring hill", "state": "FL", "postal_code": "34604", "country_code": "US" }, "phone": "3526003902", "country_code": "US" } }, "transactions": [ { "amount": { "total": "45.00", "currency": "USD", "details": { "subtotal": "45.00", "shipping": "0.00", "insurance": "0.00", "handling_fee": "0.00", "shipping_discount": "0.00" } }, "payee": { "merchant_id": "NHN6S6KT4FF6N", "email": "arunwebber2-facilitator@gmail.com" }, "description": "Payment description", "invoice_number": "5cd5404d624a9", "soft_descriptor": "PAYPAL *TESTFACILIT", "item_list": { "items": [ { "name": "Item one", "price": "45.00", "currency": "USD", "tax": "0.00", "quantity": 1 } ], "shipping_address": { "recipient_name": "Susi Flo", "line1": "Suso", "line2": "bldg", "city": "Spring hill", "state": "FL", "postal_code": "34604", "country_code": "US" } }, "related_resources": [ { "sale": { "id": "6LN25215GP1183020", "state": "completed", "amount": { "total": "45.00", "currency": "USD", "details": { "subtotal": "45.00", "shipping": "0.00", "insurance": "0.00", "handling_fee": "0.00", "shipping_discount": "0.00" } }, "payment_mode": "INSTANT_TRANSFER", "protection_eligibility": "ELIGIBLE", "protection_eligibility_type": "ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE", "transaction_fee": { "value": "2.43", "currency": "USD" }, "receipt_id": "3896118010137330", "parent_payment": "PAYID-LTKUAVA8WK14445NN137182H", "create_time": "2019-05-10T09:30:10Z", "update_time": "2019-05-10T09:30:10Z", "links": [ { "href": "https://api.sandbox.paypal.com/v1/payments/sale/6LN25215GP1183020", "rel": "self", "method": "GET" }, { "href": "https://api.sandbox.paypal.com/v1/payments/sale/6LN25215GP1183020/refund", "rel": "refund", "method": "POST" }, { "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAYID-LTKUAVA8WK14445NN137182H", "rel": "parent_payment", "method": "GET" } ], "soft_descriptor": "PAYPAL *TESTFACILIT" } } ] } ], "create_time": "2019-05-10T09:11:48Z", "update_time": "2019-05-10T09:30:10Z", "links": [ { "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAYID-LTKUAVA8WK14445NN137182H", "rel": "self", "method": "GET" } ] }

如何将其存储到我的数据库中?对于特定的用户ID,我可以通过它获取用户ID。

echo Yii::$app->user->id;

我要将此值与用户ID一起存储,该怎么办?并向用户发送付款成功消息:)

1 个答案:

答案 0 :(得分:1)

Paypal PHP-SDK为您提供setCustom(),以添加自定义字段值,您可以使用它发送用户ID,然后在执行付款后在交易对象中使用响应将其检索出来。

您使用的只是使用Paypal SDK函数的自定义组件,您应该扩展类bitcko\paypalrestapi\PayPalRestApi.php以覆盖函数checkOut()并将->setCustom(Yii::$app->user->id)添加到此链中line,因为它没有提供任何设置自定义字段的方法,因此只需将方法的整个代码复制到新类中并添加以上内容即可。

您的课程应如下所示。

注意:将文件添加到common/components文件夹中。

<?php
namespace common\components;

use bitcko\paypalrestapi\PayPalRestApi as PayPalBase;
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\Transaction;
use PayPal\Exception\PayPalConnectionException;
use yii\helpers\Url;
use Yii;

class PaypalRestApi extends PayPalBase
{

    public function checkOut($params)
    {
        $payer = new Payer();
        $payer->setPaymentMethod($params['method']);
        $orderList = [];

        foreach ($params['order']['items'] as $orderItem) {
            $item = new Item();
            $item->setName($orderItem['name'])
                ->setCurrency($orderItem['currency'])
                ->setQuantity($orderItem['quantity'])
                ->setPrice($orderItem['price']);
            $orderList[] = $item;
        }
        $itemList = new ItemList();
        $itemList->setItems($orderList);
        $details = new Details();
        $details->setShipping($params['order']['shippingCost'])
            ->setSubtotal($params['order']['subtotal']);
        $amount = new Amount();
        $amount->setCurrency($params['order']['currency'])
            ->setTotal($params['order']['total'])
            ->setDetails($details);
        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription($params['order']['description'])
            ->setCustom(Yii::$app->user->id)
            ->setInvoiceNumber(uniqid());

        $redirectUrl = Url::to([$this->redirectUrl], true);
        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl("$redirectUrl?success=true")
            ->setCancelUrl("$redirectUrl?success=false");
        $payment = new Payment();
        $payment->setIntent($params['intent'])
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions(array($transaction));
        try {
            $payment->create($this->apiContext);
            return \Yii::$app->controller->redirect($payment->getApprovalLink());
        } catch (PayPalConnectionException $ex) {
            // This will print the detailed information on the exception.
            //REALLY HELPFUL FOR DEBUGGING
            \Yii::$app->response->format = \yii\web\Response::FORMAT_HTML;
            \Yii::$app->response->data = $ex->getData();
        }
    }
}

现在将PayPalRestApicommon/config/main.phpfrontend/config/main.php组件类的配置更改为所创建的新类

'components'=> [
    ...
 'PayPalRestApi'=>[
      'class'=>'common\components\PayPalRestApi',
  ]
    ...
]

所以现在您可以通过使用

获得相同的用户ID。
$response = \yii\helpers\Json::decode( Yii::$app->PayPalRestApi->processPayment($params));
$user_id = $response['transactions'][0]['custom'];