Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

basosneo's avatar

Orders/SaveOrders/paypal

hi friends! I am following a laravel 5.2 tutorial, but I am using laravel 5.4.6, so I have so many problems...

I am now trying to create an order detail view in the admin pannel with the help of main.js and ajax.

The complementation seems to work correctly. The problem, it seems, is in the part of saving the order; This method I carry through paypal and its controller: apparently when saving the order this does not save the name or the image ...

Then when I call these two factors of the items in my modal; I get as 'name' I get 'undefined' and as image 'broken'

PaypalController.php

 <?php 

 namespace App\Http\Controllers;

 use Illuminate\Foundation\Bus\DispatchesCommands;
 use Illuminate\Routing\Controller as BaseController;
 use Illuminate\Foundation\Validation\ValidatesRequests;
 use Illuminate\Support\Facades\Input;
 use PayPal\Rest\ApiContext;
 use PayPal\Auth\OAuthTokenCredential;
 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\ExecutePayment;
 use PayPal\Api\PaymentExecution;
 use PayPal\Api\Transaction;

 use App\Order;
 use App\OrderItem;

 class PaypalController extends BaseController
 {
private $_api_context;

  public function __construct()
 {
    // setup PayPal api context
    $paypal_conf = \Config::get('paypal');
    $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
     $this->_api_context->setConfig($paypal_conf['settings']);
}

public function postPayment()
{
    $payer = new Payer();
    $payer->setPaymentMethod('paypal');

    $items = array();
    $subtotal = 0;
    $cart = \Session::get('cart');
    $currency = 'EUR';

    foreach($cart as $producto){
        $item = new Item();
        $item->setName($producto->name)
        ->setCurrency($currency)
        ->setDescription($producto->extract)
        ->setQuantity($producto->quantity)
        ->setPrice($producto->price);

        $items[] = $item;
        $subtotal += $producto->quantity * $producto->price;
    }

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

    $details = new Details();
    $details->setSubtotal($subtotal)
    ->setShipping(50);

    $total = $subtotal + 50;

    $amount = new Amount();
    $amount->setCurrency($currency)
        ->setTotal($total)
        ->setDetails($details);

    $transaction = new Transaction();
    $transaction->setAmount($amount)
        ->setItemList($item_list)
        ->setDescription('Pedido de prueba');

    $redirect_urls = new RedirectUrls();
    $redirect_urls->setReturnUrl(\URL::route('payment.status'))
        ->setCancelUrl(\URL::route('payment.status'));

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

    try {
        $payment->create($this->_api_context);
    } catch (\PayPal\Exception\PPConnectionException $ex) {
        if (\Config::get('app.debug')) {
            echo "Exception: " . $ex->getMessage() . PHP_EOL;
            $err_data = json_decode($ex->getData(), true);
            exit;
        } else {
            die('Ups! Algo salió mal');
        }
    }

    foreach($payment->getLinks() as $link) {
        if($link->getRel() == 'approval_url') {
            $redirect_url = $link->getHref();
            break;
        }
    }

    // add payment ID to session
    \Session::put('paypal_payment_id', $payment->getId());

    if(isset($redirect_url)) {
        // redirect to paypal
        return \Redirect::away($redirect_url);
    }

    return \Redirect::route('cart-show')
        ->with('error', 'Ups! Error desconocido.');

    }

    public function getPaymentStatus()
    {
    // Get the payment ID before session clear
    $payment_id = \Session::get('paypal_payment_id');

    // clear the session payment ID
    \Session::forget('paypal_payment_id');

    $payerId = \Input::get('PayerID');
    $token = \Input::get('token');

    //if (empty(\Input::get('PayerID')) || empty(\Input::get('token'))) {
    if (empty($payerId) || empty($token)) {
        return \Redirect::route('home')
            ->with('message', 'Hubo un problema al intentar pagar con Paypal');
    }

    $payment = Payment::get($payment_id, $this->_api_context);

    // 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 = new PaymentExecution();
    $execution->setPayerId(\Input::get('PayerID'));

    //Execute the payment
    $result = $payment->execute($execution, $this->_api_context);

    //echo '<pre>';print_r($result);echo '</pre>';exit; // DEBUG RESULT, remove it later

    if ($result->getState() == 'approved') { // payment made
        // Registrar el pedido --- ok
        // Registrar el Detalle del pedido  --- ok
        // Eliminar carrito 
        // Enviar correo a user
        // Enviar correo a admin
        // Redireccionar

        $this->saveOrder(\Session::get('cart'));

        \Session::forget('cart');


        return \Redirect::route('home')
            ->with('message', 'Compra realizada de forma correcta');
    }
    return \Redirect::route('home')
        ->with('message', 'La compra fue cancelada');
}


private function saveOrder($cart)
{
    $subtotal = 0;
    foreach($cart as $item){
        $subtotal += $item->price * $item->quantity;
    }
    
    $order = Order::create([
        'subtotal' => $subtotal,
        'shipping' => 50,
        'user_id' => \Auth::user()->id
    ]);
    
    foreach($cart as $item){
        $this->saveOrderItem($item, $order->id);
    }
}

private function saveOrderItem($item, $order_id)
{
    OrderItem::create([
        'quantity' => $item->quantity,
        'price' => $item->price,
        'product_id' => $item->id,
        'order_id' => $order_id,
        'name' => $item->name


    ]);
}

  }

admin.main.js

    $(document).ready(function(){

  $(".btn-detalle-pedido").on('click', function(e){
    e.preventDefault();

    var id_pedido = $(this).data('id');
    var path = $(this).data('path');
    var token = $(this).data('token');
    var modal_title = $(".modal-title");
    var modal_body = $(".modal-body");
    var loading = '<p><i class="fa fa-circle-o-notch fa-spin"></i> Cargando datos</p>';
    var table = $("#table-detalle-pedido tbody");
    var data = {'_token' : token, 'order_id' : id_pedido};

    modal_title.html('Detalle del Pedido: ' + id_pedido);
    table.html(loading);

    $.post(
        path,
        data,
        function(data){
            //console.log(response);
            table.html("");
            
            for(var i=0; i<data.length; i++){
                
                var fila = "<tr>";
                fila += "<td><img src='" + data[i].image + "' width='30'></td>";
                fila += "<td>" + data[i].name + "</td>";
                fila += "<td>$ " + parseFloat(data[i].price).toFixed(2) + "</td>";
                fila += "<td>" + parseInt(data[i].quantity) + "</td>";
                fila += "<td>$ " + (parseFloat(data[i].quantity) * parseFloat(data[i].price)).toFixed(2) + "</td>";
                fila += "</tr>";
                
                table.append(fila);
            }
        },
        'json'
    );

});


 });

Modal

0 likes
1 reply

Please or to participate in this conversation.