Yii2 PayPal интеграции платежей - PullRequest
1 голос
/ 10 мая 2019

Я использую это 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));
        }

Все прошло, как я и ожидал, этот звонок возвращает что-то подобное этому.

{ "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" } ] }

Как я могу сохранить это в моей базе данных? для идентификатора пользователя specefi я могу получить идентификатор пользователя с этим.

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

Я хочу сохранить это значение вместе с идентификатором пользователя, как я могу это сделать? И сообщение об успешной оплате пользователю:)

1 Ответ

1 голос
/ 11 мая 2019

Paypal PHP-SDK Предоставляет вам setCustom() для добавления значения настраиваемого поля, вы можете использовать его для отправки идентификатора пользователя, а затем получить его с ответом в объекте транзакции после оплаты казнены.

То, что вы используете - это просто пользовательский компонент, использующий функции Paypal SDK, вы должны расширить класс bitcko\paypalrestapi\PayPalRestApi.php, чтобы переопределить функцию checkOut() и добавить ->setCustom(Yii::$app->user->id) в цепочку в этой строке , поскольку он не предоставляет никакого способа установки настраиваемого поля, поэтому просто скопируйте весь код метода в ваш новый класс и добавьте приведенное выше.

Ваш класс должен выглядеть ниже.

ПРИМЕЧАНИЕ. Добавьте файл в папку 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();
        }
    }
}

Теперь измените ваши конфигурации для класса компонента PayPalRestApi в common/config/main.php или frontend/config/main.php, в зависимости от того, что вы используете, на новый класс, который вы создали

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

так что теперь вы можете получить тот же идентификатор пользователя, используя

$response = \yii\helpers\Json::decode( Yii::$app->PayPalRestApi->processPayment($params));
$user_id = $response['transactions'][0]['custom'];
...