PayPal Transaction API Get Total не является допустимым значением цифры c - PullRequest
1 голос
/ 24 января 2020

Я перепробовал все, и я не уверен, почему я получаю сообщение об ошибке "Итоговое значение не является действительным числом c значение". Все в порядке, пока я не попытаюсь добавить доставку и налог на детали $. Когда я возвращаю данные в $, я получаю это {"shipping": "49.99", "tax": "0.12", "subtotal": "50.81"}. Все из $ request нормально я просто не понимаю что я делаю не так. Кажется, все складывается не всегда, я получаю ошибку.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Sold_Item;
use App\Customer_Order;
use Auth;
use Session;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendOrder;
use App\Mail\OrderConfirmation;
use Carbon\Carbon;
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\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;

class PaypalController extends Controller
{



    public function payment(Request $request){  
          if (empty($request->contact_name) || empty($request->phone_number) || empty($request->email_address) || empty($request->address) || empty($request->country) || empty($request->spr) || empty($request->city) || empty($request->zipcode)) {
            return back()->withErrors(['error','Error Please Retry']);
        }else{


                $apiContext = new \PayPal\Rest\ApiContext(
                  new \PayPal\Auth\OAuthTokenCredential(
                    "AaOWETQOsvghR3ih4FfxrTLwEWMDPUqfPw7wK9d4pTNF9i546wgN4X6eGvMdffl7qk9JCj5YsauIV0cc",
                    "EMMCcMlheBQjBgnWY_SIDt9GISV_Vu5ha-BelnJHUEx3kB6TqsPsBp0kKuA6A2HJY2MgFyo4ZaiPkQGl"
                  )
                );


                $apiContext->setConfig(
                    array(
                        'mode' => 'live',
                        'log.LogEnabled' => true,
                        'log.FileName' => 'PayPal.log',
                        'log.LogLevel' => 'FINE', // PLEASE USE `FINE` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
                        'cache.enabled' => true,
                         'validation.level' => 'log'

                    )
                );

                $payer = new Payer();
                $payer->setPaymentMethod("paypal");

                // Set redirect URLs
                $redirectUrls = new RedirectUrls();
                $redirectUrls->setReturnUrl('https://beneplants.com/process')
                  ->setCancelUrl('https://beneplants.com/shopcart');

                $k = 1;
                $rrr = array();
                $total_price =0;

                foreach(session('cart') as $sku => $itemss){
                    $total_price += $itemss['price'];
                    ${"item_".$k} = new Item();
                    $rrr[] = ${"item_".$k}->setName($itemss['name']) /** item name **/
                    ->setCurrency('CAD')
                    ->setQuantity(1)
                    ->setPrice($itemss['price']); /** unit price **/
                    $k++;
                }


                $item_list = new ItemList();
                $item_list->setItems($rrr);

                $total_price += $request->shipping_cost;
                $total_price += $request->tax;

                $details = new Details();
                $details->setShipping($request->shipping_cost)
                    ->setTax($request->tax)
                    ->setSubtotal($total_price);

                $amount = new Amount();
                $amount->setCurrency("CAD")
                  ->setTotal($details);


                // Set transaction object
                $transaction = new Transaction();
                $transaction->setAmount($amount)
                ->setItemList($item_list)
                ->setDescription('Your transaction description');
                // Create the full payment object

                $payment = new Payment();
                $payment->setIntent('sale')
                  ->setPayer($payer)
                  ->setRedirectUrls($redirectUrls)
                  ->setTransactions(array($transaction));

                try {
                  $payment->create($apiContext);

                  $customer_order = [
                    "contact_name" => $request->contact_name,
                    "email_address"=>$request->email_address,
                    "phone_number" => $request->phone_number,
                    "address" => $request->address,
                    "unit" => $request->unit,
                    "country" => $request->country,
                    "spr" => $request->spr,
                    "city" => $request->city,
                    "zipcode" => $request->zipcode,
                    "total_price"=>$request->total,
                    "shipping_cost"=>$request->shipping_cost,
                    "tax"=>$request->tax
                  ];


                  session()->put('paypal', $customer_order);

                  // Get PayPal redirect URL and redirect the customer
                  $approvalUrl = $payment->getApprovalLink();
               //   $approvalUrl = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
                  return redirect($approvalUrl);

                  // Redirect the customer to $approvalUrl
                } catch (PayPal\Exception\PayPalConnectionException $ex) {
                  echo $ex->getCode();
                  echo $ex->getData();
                  die($ex);
                } catch (Exception $ex) {
                  die($ex);
                }



        }
    }

1 Ответ

1 голос
/ 24 января 2020

У вас есть этот кусок кода:

$details = new Details();
$details->setShipping($request->shipping_cost)
        ->setTax($request->tax)
        ->setSubtotal($total_price);

$amount = new Amount();
$amount->setCurrency("CAD")
       ->setTotal($details); //<--HERE

Видите, вы используете объект класса Details в качестве значения для setTotal(). Я считаю, что вам нужно заменить ->setTotal($details); на ->setTotal($total_price);

...