Вызов неопределенного метода createMonthlySubscription () - PullRequest
0 голосов
/ 19 апреля 2019

Я использую пакет https://github.com/srmklive/laravel-paypal, и я пытаюсь использовать повторяющийся метод PayPal для ежемесячных подписок, он возвращает ошибку ниже:

Call to undefined method Srmklive\PayPal\Services\ExpressCheckout::createMonthlySubscription()

код

//controller head
use Srmklive\PayPal\Services\ExpressCheckout;
use Srmklive\PayPal\Services\AdaptivePayments;


public function getExpressCheckout(Request $request)
    {
        $recurring = ($request->get('mode') === 'recurring') ? true : false;
        $cart = $this->getCheckoutData($recurring);
        try {
            $response = $this->provider->setExpressCheckout($cart, $recurring);
            return redirect($response['paypal_link']);
        } catch (\Exception $e) {
            $invoice = $this->createInvoice($cart, 'Invalid');
            session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
        }
    }

    public function getExpressCheckoutSuccess(Request $request)
    {
        // dd($request->all());
        $Itemm = Type::where('id', $request->input('type_id'))->first();
        $recurring = ($request->get('mode') === 'recurring') ? true : false;
        $token = $request->get('token');
        $PayerID = $request->get('PayerID');
        $cart = $this->getCheckoutData($recurring);
        // Verify Express Checkout Token
        $response = $this->provider->getExpressCheckoutDetails($token);
        if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
            if ($recurring === true) {
                $response = $this->provider->createMonthlySubscription($response['TOKEN'], $cart['item']['price'], $cart['subscription_desc']);
                if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
                    $status = 'Processed';
                } else {
                    $status = 'Invalid';
                }
            } else {
                // Perform transaction on PayPal
                $payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
                dd($payment_status);
                $status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
            }
            $invoice = $this->createInvoice($cart, $status);
            if ($invoice->paid) {
                session()->put(['code' => 'success', 'message' => "Order $invoice->id has been paid successfully!"]);
                $user = Auth::user();
                Mail::to($user->email)->send(new UserPlanActivated($user));
            } else {
                session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
            }
            return redirect('/');
        }
    }

    public function getAdaptivePay()
    {
        $this->provider = new AdaptivePayments();
        $data = [
            'receivers'  => [
                [
                    'email'   => 'johndoe@example.com',
                    'amount'  => 10,
                    'primary' => true,
                ],
                [
                    'email'   => 'janedoe@example.com',
                    'amount'  => 5,
                    'primary' => false,
                ],
            ],
            'payer'      => 'EACHRECEIVER', // (Optional) Describes who pays PayPal fees. Allowed values are: 'SENDER', 'PRIMARYRECEIVER', 'EACHRECEIVER' (Default), 'SECONDARYONLY'
            'return_url' => url('payment/success'),
            'cancel_url' => url('payment/cancel'),
        ];
        $response = $this->provider->createPayRequest($data);
        dd($response);
    }

    public function notify(Request $request)
    {
        if (!($this->provider instanceof ExpressCheckout)) {
            $this->provider = new ExpressCheckout();
        }
        $post = [
            'cmd' => '_notify-validate',
        ];
        $data = $request->all();
        foreach ($data as $key => $value) {
            $post[$key] = $value;
        }
        $response = (string) $this->provider->verifyIPN($post);
        $ipn = new IPNStatus();
        $ipn->payload = json_encode($post);
        $ipn->status = $response;
        $ipn->save();
        // $user = Auth::user();
        // Mail::to($user->email)->send(new UserPlanActivated($user));
    }

    protected function getCheckoutData($recurring = false)
    {
        $data = [];
        $order_id = Invoice::all()->count() + 1;

        $Itemm = Type::where('id', \Request::input('type_id'))->first();

        // dd($Itemm['name']);
        if ($recurring === true) {
            $data['items'] = [
                [
                    'name'  => 'Monthly Subscription '.$Itemm['name'].' #'.$order_id,
                    'price' => $Itemm['price'],
                    'qty'   => 1,
                ],
            ];
            // $data['return_url'] = route('userec?mode=recurring');
            $data['return_url'] = url('/paypal/ec-checkout-success?mode=recurring');
            $data['subscription_desc'] = 'Monthly Subscription '.$Itemm['name'].' #'.$order_id;
        } else {
            $data['items'] = [
                [
                    'name'  => 'Monthly Subscription '.$Itemm['name'].' #'.$order_id,
                    'price' => $Itemm['price'],
                    'qty'   => 1,
                ],
            ];
            // $data['return_url'] = route('userec');
            $data['return_url'] = url('/paypal/ec-checkout-success');
        }
        $data['invoice_id'] = $Itemm['name'].'_'.$order_id;
        $data['invoice_description'] = "Order #$order_id Invoice";
        $data['cancel_url'] = route('userpackages');
        $total = 0;
        foreach ($data['items'] as $item) {
            $total += $item['price'] * $item['qty'];
        }
        $data['total'] = $total;
        return $data;
    }

    protected function createInvoice($cart, $status)
    {
        $current = Carbon::now();
        $expiredatetime = $current->addDays(30);


        $invoice = new Invoice();
        $invoice->user_id = Auth::user()->id;
        $invoice->title = $cart['invoice_description'];
        $invoice->price = $cart['total'];
        $invoice->plan_expire = $expiredatetime->toDateTimeString();

        collect($cart['items'])->each(function ($product) use ($invoice) {
            $invoice->type_id = 3;
        });

        if (!strcasecmp($status, 'Completed') || !strcasecmp($status, 'Processed')) {
            $invoice->paid = 1;
        } else {
            $invoice->paid = 0;
        }
        $invoice->save();
        return $invoice;
}

Примечание

Моя ошибка исходит из этой строки в getExpressCheckoutSuccess функции:

$response = $this->provider->createMonthlySubscription($response['TOKEN'], $cart['item']['price'], $cart['subscription_desc']);

К сожалению, заставить разработчика этого пакета ответить на вопросы mission impossible! Так что я просто надеюсь, что кто-то здесь имеет опыт работы с похожая проблема и знаю, как ее исправить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...