Я тоже извиняюсь и знаю, что мои коды действительно ужасны. Как я могу получить значения в корзине, даже если это плохая практика, я действительно не понимаю.Я новичок в этом интегрированном платеже 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') ИЛИ завершено ('Прямой доступ к сценарию запрещен');
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;
}
}
ShoppingCartView
<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: <?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>