Как получить значения корзины в codeigniter для оплаты PayPal

Я тоже извиняюсь, и я знаю, что мои коды действительно уродливые. Как я могу получить значения в тележке, даже если это не так, я действительно не понимаю. Я новичок в этой интеграции платежей PayPal

Контроллер Paypal

  <?php if (!defined('BASEPATH')) exit('No direct script access 
  allowed');

  require_once(APPPATH . 'libraries/paypal-php-sdk/paypal/rest-api-sdk- 
  php/sample/bootstrap.php'); // require paypal files


  use PayPal\Api\ItemList;
  use PayPal\Api\Payment;
  use PayPal\Api\RedirectUrls;
  use PayPal\Api\Amount;
  use PayPal\Api\PaymentExecution;
  use PayPal\Api\RefundRequest;
  use PayPal\Api\Sale;

 class Paypal extends CI_Controller
 {
 public $_api_context;

 function  __construct()
  {
    parent::__construct();
    $this->load->model('paypal_model', 'paypal');
    // paypal credentials
    $this->config->load('paypal');

    $this->_api_context = new \PayPal\Rest\ApiContext(
        new \PayPal\Auth\OAuthTokenCredential(
            $this->config->item('client_id'), $this->config- 
    >item('secret')
        )
    );
   }

 function index(){
    $this->load->view('content/payment_credit_form');
}


 function create_payment_with_paypal()
  {

    // setup PayPal api context
    $this->_api_context->setConfig($this->config->item('settings'));


  // ### Payer
 // A resource representing a Payer that funds a payment
 // For direct credit card payments, set payment method
 // to 'credit_card' and add an array of funding instruments.

    $payer['payment_method'] = 'paypal';

    // ### Itemized information
    // (Optional) Lets you specify item wise
  // information
    $item1["name"] = $this->input->post('item_name');
    $item1["sku"] = $this->input->post('item_number');  // Similar to 
   `item_number` in Classic API
    $item1["description"] = $this->input->post('item_description');
    $item1["currency"]  = "USD";
    $item1["quantity"] =1;
    $item1["price"] = $this->input->post('item_price');

    $itemList = new ItemList();
    $itemList->setItems(array($item1));

     // ### Additional payment details
     // Use this optional field to set additional
     // payment information such as tax, shipping
    // charges etc.
    $details['tax'] = $this->input->post('details_tax');
    $details['subtotal'] = $this->input->post('details_subtotal');
    // ### Amount
    // Lets you specify a payment amount.
    // You can also specify additional details
    // such as shipping, tax.
    $amount['currency'] = "USD";
    $amount['total'] = $details['tax'] + $details['subtotal'];
    $amount['details'] = $details;
     // ### Transaction
    // A transaction defines the contract of a
     // payment - what is the payment for and who
    // is fulfilling it.
    $transaction['description'] ='Payment description';
    $transaction['amount'] = $amount;
    $transaction['invoice_number'] = uniqid();
    $transaction['item_list'] = $itemList;

    // ### Redirect urls
    // Set the urls that the buyer must be redirected to after
    // payment approval/ cancellation.
    $baseUrl = base_url();
    $redirectUrls = new RedirectUrls();
    $redirectUrls->setReturnUrl($baseUrl."paypal/getPaymentStatus")
        ->setCancelUrl($baseUrl."paypal/getPaymentStatus");

    // ### Payment
    // A Payment Resource; create one using
     // the above types and intent set to sale 'sale'
    $payment = new Payment();
    $payment->setIntent("sale")
        ->setPayer($payer)
        ->setRedirectUrls($redirectUrls)
        ->setTransactions(array($transaction));

    try {
        $payment->create($this->_api_context);
    } catch (Exception $ex) {
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL 
     CODE. FOR SAMPLE ONLY
        ResultPrinter::printError("Created Payment Using PayPal. Please 
      visit the URL to Approve.", "Payment", null, $ex);
        exit(1);
    }
    foreach($payment->getLinks() as $link) {
        if ($link->getRel() == 'approval_url') {
            $redirect_url = $link->getHref();
            break;
        }
     }

    if (isset($redirect_url)) {
        /** redirect to paypal **/
        redirect($redirect_url);
    }

    $this->session->set_flashdata('success_msg','Unknown error 
    occurred');
    redirect('paypal/index');

    }


    public function getPaymentStatus()
    {

    // paypal credentials

    /** Get the payment ID before session clear **/
    $payment_id = $this->input->get("paymentId") ;
    $PayerID = $this->input->get("PayerID") ;
    $token = $this->input->get("token") ;
    /** clear the session payment ID **/

    if (empty($PayerID) || empty($token)) {
        $this->session->set_flashdata('success_msg','Payment failed');
        redirect('paypal/index');
    }

    $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($this->input->get('PayerID'));

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



    //  DEBUG RESULT, remove it later **/
    if ($result->getState() == 'approved') {
        $trans = $result->getTransactions();

        // item info
        $Subtotal = $trans[0]->getAmount()->getDetails()- 
     >getSubtotal();
        $Tax = $trans[0]->getAmount()->getDetails()->getTax();

        $payer = $result->getPayer();
        // payer info //
        $PaymentMethod =$payer->getPaymentMethod();
        $PayerStatus =$payer->getStatus();
        $PayerMail =$payer->getPayerInfo()->getEmail();

        $relatedResources = $trans[0]->getRelatedResources();
        $sale = $relatedResources[0]->getSale();
        // sale info //
        $saleId = $sale->getId();
        $CreateTime = $sale->getCreateTime();
        $UpdateTime = $sale->getUpdateTime();
        $State = $sale->getState();
        $Total = $sale->getAmount()->getTotal();
        /** it's all right **/
        /** Here Write your database logic like that insert record or 
        value in database if you want **/
        $this->paypal- 

      >create($Total,$Subtotal,$Tax,$PaymentMethod,
      $PayerStatus,$PayerMail,$saleI 
         d,$CreateTime,$UpdateTime,$State);
        $this->session->set_flashdata('success_msg','Payment success');
        redirect('paypal/success');
    }
    $this->session->set_flashdata('success_msg','Payment failed');
    redirect('paypal/cancel');
   }
   function success(){
    $this->load->view("content/success");
  }
  function cancel(){
    $this->load->view("content/cancel");
   }

   function load_refund_form(){
    $this->load->view('content/Refund_payment_form');
    }

     function refund_payment(){
    $refund_amount = $this->input->post('refund_amount');
    $saleId = $this->input->post('sale_id');
    $paymentValue =  (string) round($refund_amount,2); ;

       // ### Refund amount
      // and refunded fee (to Payee). Use the $amt->details
     // field to mention fees refund details.
    $amt = new Amount();
    $amt->setCurrency('USD')
        ->setTotal($paymentValue);

     // ### Refund object
     $refundRequest = new RefundRequest();
     $refundRequest->setAmount($amt);

      // ###Sale
      // A sale transaction.
      // Create a Sale object with the
     // given sale transaction id.
    $sale = new Sale();
    $sale->setId($saleId);
    try {
        // Refund the sale
        // (See bootstrap.php for more on `ApiContext`)
        $refundedSale = $sale->refundSale($refundRequest, $this- 
         >_api_context);
        } catch (Exception $ex) {
        // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL 
        CODE. FOR SAMPLE ONLY
        ResultPrinter::printError("Refund Sale", "Sale", null, 
        $refundRequest, $ex);
        exit(1);
      }


    ResultPrinter::printResult("Refund Sale", "Sale", $refundedSale- 
     >getId(), $refundRequest, $refundedSale);

    return $refundedSale;
      }
       }

Контроллер тележки для покупок

<?php

определено ('BASEPATH') OR exit ('Прямой доступ к сценарию не разрешен');

   class Shopping_cart extends CI_Controller {


  function index()
  {

   $this->load->model("shopping_cart_model");
   $data["product"] = $this->shopping_cart_model->fetch_all();
  $data["daterange"] = $this- 
  >getDatesFromRange($_SESSION["profile_data"] 
  ['startdate'],$_SESSION["profile_data"]['enddate']);
   $this->load->library('cart');
   $this->load->view("shopping_cart", $data);


   if (isset($_POST['submitbtn'])){
   foreach($this->cart->contents() as $items)
    {
    $status = "ON-GOING";    
    $data = array(

    "product_name"   => $items["name"],
    "quantity"       => $items["qty"],
    "product_price"  => $items["price"],
    "username" => $_SESSION["profile_data"]["username"],
    'mobilenum' => $_SESSION["profile_data"]['mobilenum'],
    'homeadd' => $_SESSION["profile_data"]['homeadd'],
    'startdate' => $_SESSION["profile_data"]['startdate'],
    'enddate' => $_SESSION["profile_data"]['enddate'],
    'place_type' => $_SESSION["profile_data"]['place_type'],
    'time' => $_SESSION["profile_data"]['time'],
    'status' => $status,
    'total' => $items["subtotal"],


  );
  $this->db->insert('occasion', $data);
  $this->session->set_flashdata("success", "You successfully been 
  reserved");
   redirect("shopping_cart","refresh");

    }

    }       


   }

  function add()
  {
  $this->load->library("cart");
   $data = array(
   "id"  => $_POST["product_id"],
   "name"  => $_POST["product_name"],
    "qty"  => $_POST["quantity"],
   "price"  => $_POST["product_price"],
   "place_type" => $_SESSION["profile_data"]['place_type']

  );
 $this->cart->insert($data); //return rowid 
 echo $this->view();
  }

 function load()
  {
 echo $this->view();
  }

 function remove()
  {
  $this->load->library("cart");
 $row_id = $_POST["row_id"];
   $data = array(
  'rowid'  => $row_id,
  'qty'  => 0
   );
$this->cart->update($data);
   echo $this->view();
   }

 function clear()
  {
 $this->load->library("cart");
  $this->cart->destroy();
  echo $this->view();
  }

 function getDatesFromRange($start, $end, $format='Y-m-d') {
    return array_map(function($timestamp) use($format) {
        return date($format, $timestamp);
    },
    range(strtotime($start) + ($start < $end ? 4000 : 8000), 
    strtotime($end) + ($start < $end ? 8000 : 4000), 86400));
 }

function view()
 {
 $this->load->library("cart");
 $output = '';
 $output .= '
<h3>Rental Carts</h3><br />
 <div class = "table-responsive">
 <div align = "right">
<button type = "button" id = "clear_cart" class = "btn btn-warning">Clear 
 Cart</button>
 </div>
  <br />
  <table class = "table table-bordered">
 <tr>
 <th width = "40%">Name</th>
 <th width = "15%">Quantity</th>
 <th width = "15%">Price</th>
 <th width = "15%">Total</th>
 <th width = "15%">Action</th>
 </tr>

 ';
  $count = 0;
 foreach($this->cart->contents() as $items)
  {
 $count++;
  $output .='

<tr> 
<td>'.$items["name"].' <input type = "hidden" id = "cart_name" 
name = "cart_name" value = "'.$items["name"].'" /></td>
<td>'.$items["qty"].' <input type = "hidden" id = "cart_qty" 
 name = "cart_qty" value = "'.$items["qty"].'" /></td>
<td>'.$items["price"].' <input type = "hidden" id = "cart_price" 
 name = "cart_price" value = "'.$items["price"].'" /></td>
<td>'.$items["subtotal"].'</td> 

<td><button type = "button" name = "remove" class = "btn btn-danger btn-xs 
 remove_inventory" id = "'.$items["rowid"].'">Remove</button></td>
   </tr>
   ';
  }
   $output .= '
    <tr>
   <td colspan = "4" align = "right">Total</td>
   <td>'.$this->cart->total().'</td>
  </tr>
  </table>

   </div>
   ';

  if ($count == 0)
   {
   $output = '<h3 align = "center">Cart is Empty</h3>';

   }
    return $output;
     }
     }

Покупки

 <h3 align = "center">AOZ RESERVATION PRODUCTS RENTALS</h3>

<?php if (isset($_SESSION['success'])) { ?>
    <div class = "alert alert-success"> <?php echo $_SESSION['success']; 
   ?></div>
<?php  } ?>

<form action = "" method = "POST">

<?php
    $numItems = count($product);
    $i = 0;
    foreach($product as $row) {
    $i++;
     ?>

    <div class = "container">
        <div class = "row">
           <div class = "col-md-4 col-xs-12">
            <img src = "<?php echo base_url().'images/'.$row- 
             >product_image; ?>"
                 class = "img-thumbnail" 
                 alt = "<?php echo $row->product_name; ?>"
                 style = "max-width: 300px;" />
        </div>
        <div class = "col-md-8 col-xs-12">
            <h4><?php echo $row->product_name; ?></h4>
            <p>Description:&nbsp<?php echo $row->description; ?></p>


            <h3 class = "text-danger"><?php echo $row->product_price; ?> 
            PHP</h3>

            <input type = "text" name = "quantity" class = "form-control 
          quantity" id = "<?php echo $row->product_id; ?>" /><br />

            <input type = "button" name = "add_cart" 
                    class = "btn btn-success add_cart" 
                    data-productname = "<?php echo $row->product_name; ? 
                >" 
                    data-price = "<?php echo $row->product_price; ?>" 
                    data-productid = "<?php echo  $row->product_id; ?>" 
                    value = "Add to Reserve"
            />
         </div>
      </div>
    </div>

   <?php if ($i != $numItems){ ?>
      <hr style = "width: 80%;" />
    <?php } ?>



   <?php } ?>   

   <div class = "col-lg-6 col-md-6">
    <div id = "cart_details">
        <h3 align = "center">Cart is Empty</h3>
    </div>
    <button id = "submitbtn" name = "submitbtn" style = "display:none;" 
  class = "btn btn-success">Submit</button>
   </div>    

   </form>    

<script src = "<?php echo base_url().'assests/jquery/jquery- 
  3.1.0.min.js'; ?>"></script>
<script src = "<?php echo 
 base_url().'assests/bootstrap/js/bootstrap.min.js'; ?>"></script>

 </body>
</html>
 <script>
 $(document).ready(function(){

  $('.add_cart').click(function(){
  var product_id = $(this).data("productid");
  var product_name = $(this).data("productname");
  var product_price = $(this).data("price");
  var daterange = <?php echo json_encode(count($daterange));?>;
   var quantity = $('#' + product_id).val();
  if (quantity != '' && quantity > 0)
  {
  $.ajax({
  url:"<?php echo base_url(); ?>index.php/shopping_cart/add",
   method:"POST",
 data:{product_id:product_id, product_name:product_name, 
  product_price:product_price * daterange, quantity:quantity},
   success:function(data)
   {
   // alert("Product Added into Cart");
   $('#cart_details').html(data);
   $('#' + product_id).val('');
   $("#submitbtn").css("display", "block");
   }
   });
  }
  else
  {
  alert("Please Enter quantity");
 }
  });

 $('#cart_details').load("<?php echo base_url(); ? 
>index.php/shopping_cart/load");

 $(document).on('click', '.remove_inventory', function(){
 var row_id = $(this).attr("id");
  if (confirm("Are you sure you want to remove this?"))
  {
  $.ajax({
  url:"<?php echo base_url(); ?>index.php/shopping_cart/remove",
   method:"POST",
   data:{row_id:row_id},
  success:function(data)
  {
 alert("Product removed from Cart");
 $('#cart_details').html(data);
  }
  });
 }
 else
 {
 return false;
  }
  });

 $(document).on('click', '#clear_cart', function(){
  if (confirm("Are you sure you want to clear cart?"))
   {
  $.ajax({
    url:"<?php echo base_url(); ?>index.php/shopping_cart/clear",
     success:function(data)
     {
      alert("Your cart has been clear...");
     $('#cart_details').html(data);
      }
       });
        }
    else
       {
    return false;
        }
    });

       });
    </script>
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Оживление вашего приложения Laravel: Понимание режима обслуживания
Оживление вашего приложения Laravel: Понимание режима обслуживания
Здравствуйте, разработчики! В сегодняшней статье мы рассмотрим важный аспект управления приложениями, который часто упускается из виду в суете...
Установка и настройка Nginx и PHP на Ubuntu-сервере
Установка и настройка Nginx и PHP на Ubuntu-сервере
В этот раз я сделаю руководство по установке и настройке nginx и php на Ubuntu OS.
Коллекции в Laravel более простым способом
Коллекции в Laravel более простым способом
Привет, читатели, сегодня мы узнаем о коллекциях. В Laravel коллекции - это способ манипулировать массивами и играть с массивами данных. Благодаря...
Как установить PHP на Mac
Как установить PHP на Mac
PHP - это популярный язык программирования, который используется для разработки веб-приложений. Если вы используете Mac и хотите разрабатывать...
2
0
854
1

Ответы 1

Похоже, вы здесь работаете с Платежный стандарт PayPal, а это значит, что вам нужно добавить переменные отдельных элементов для позиций.

Это должно сработать для вас, но если вы хотите больше свободы и гибкости при интеграции в целом, вы захотите переключиться на API-интерфейсы оформления заказа вместо использования PayPal Standard.

У нас есть PHP SDK для PayPal, который делает это очень просто. Вы можете установить его в CodeIgniter с помощью Composer, и он включает образцы и сценарии шаблонов для каждого вызова API, предлагаемого PayPal. Вы просто вводите значения для любого вызова, с которым работаете, а он делает все остальное.

Другие вопросы по теме