Paypal Integration With Codeigniter
Important links
https://github.com/paypal/
Paypal.php Config file
<?php
/** set your paypal credential **/
$config['client_id'] = 'AYi10safNdkX9w4w6MczQe_AfryNYeD0UNHXOLIP',KXybxd';
$config['secret'] = 'EOJnyv3L-JcbquvkUc7XOWpgdNUBj9H0l4PhVZvzdnfghsH1J974';
/**
* SDK configuration
*/
/**
* Available option 'sandbox' or 'live'
*/
$config['settings'] = array(
'mode' => 'sandbox',
/**
* Specify the max request time in seconds
*/
'http.ConnectionTimeOut' => 1000,
/**
* Whether want to log to a file
*/
'log.LogEnabled' => true,
/**
* Specify the file that want to write on
*/
'log.FileName' => 'application/logs/paypal.log',
/**
* Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
*
* Logging is most verbose in the 'FINE' level and decreases as you
* proceed towards ERROR
*/
'log.LogLevel' => 'FINE'
);
Paypal.php Controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
include_once './vendor/autoload.php';
use PayPal\Api\ItemList;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\PaymentExecution;
class Paypal extends CI_Controller
{
public $_api_context;
function __construct()
{
parent::__construct();
$this->load->library('session');
$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('include/header');
$this->load->view('content/buy_form');
$this->load->view('include/footer');
}
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()
{
// echo "<pre>";
// print_r($this->input->get());exit;
// 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);
// echo "<pre>";
// print_r($result);exit;
// 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,$saleId,$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('include/header');
$this->load->view('content/success');
$this->load->view('include/footer');
}
function cancel(){
$this->paypal->create_payment();
$this->load->view('include/header');
$this->load->view('content/cancel');
$this->load->view('include/footer');
}
}
Paypal_model.php Model
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Paypal_model extends CI_Model {
function __construct() {
parent::__construct();
}
/* This function create new Service. */
function create($Total,$SubTotal,$Tax,$PaymentMethod,$PayerStatus,$PayerMail,$saleId,$CreateTime,$UpdateTime,$State) {
$this->db->set('txn_id',$saleId);
$this->db->set('PaymentMethod',$PaymentMethod);
$this->db->set('PayerStatus',$PayerStatus);
$this->db->set('PayerMail',$PayerMail);
$this->db->set('Total',$Total);
$this->db->set('SubTotal',$SubTotal);
$this->db->set('Tax',$Tax);
$this->db->set('Payment_state',$State);
$this->db->set('CreateTime',$CreateTime);
$this->db->set('UpdateTime',$UpdateTime);
$this->db->insert('payments');
$id = $this->db->insert_id();
return $id;
}
}
buy_form.php View
<div class="container">
<div class="starter-template">
<h1>PayPal Payment</h1>
<p class="lead">Pay Now</p>
</div>
<div class="contact-form">
<p class="notice error"><?= $this->session->flashdata('error_msg') ?></p><br/>
<p class="notice error"><?= $this->session->flashdata('success_msg') ?></p><br/>
<form method="post" class="form-horizontal" role="form" action="<?= base_url() ?>paypal/create_payment_with_paypal">
<fieldset>
<input title="item_name" name="item_name" type="hidden" value="Test Item">
<input title="item_number" name="item_number" type="hidden" value="12345">
<input title="item_description" name="item_description" type="hidden" value="to buy samsung smart tv">
<input title="item_tax" name="item_tax" type="hidden" value="1">
<input title="item_price" name="item_price" type="hidden" value="3">
<input title="details_tax" name="details_tax" type="hidden" value="3">
<input title="details_subtotal" name="details_subtotal" type="hidden" value="3">
<div class="form-group">
<div class="col-sm-offset-5">
<button type="submit" class="btn btn-success">Pay Now</button>
</div>
</div>
</fieldset>
</form>
</div>
</div><!-- /.container -->
success.php View
<div class="container">
<div class="starter-template">
<h1>PayPal Payment</h1>
<p class="lead">Pay Now</p>
</div>
<div class="contact-form">
<p class="notice error"><?= $this->session->flashdata('error_msg') ?></p><br/>
<p class="notice error"><?= $this->session->flashdata('success_msg') ?></p><br/>
<form method="post" class="form-horizontal" role="form" action="<?= base_url() ?>paypal/create_payment_with_paypal">
<fieldset>
<input title="item_name" name="item_name" type="hidden" value="ahmed fakhr">
<input title="item_number" name="item_number" type="hidden" value="12345">
<input title="item_description" name="item_description" type="hidden" value="to buy samsung smart tv">
<input title="item_tax" name="item_tax" type="hidden" value="1">
<input title="item_price" name="item_price" type="hidden" value="7">
<input title="details_tax" name="details_tax" type="hidden" value="7">
<input title="details_subtotal" name="details_subtotal" type="hidden" value="7">
<div class="form-group">
<div class="col-sm-offset-5">
<button type="submit" class="btn btn-success">Pay Now</button>
</div>
</div>
</fieldset>
</form>
</div>
</div><!-- /.container -->
cancel.php View
<div class="container">
<div class="starter-template">
<h1>PayPal Payment</h1>
<p class="lead">Canceld order</p>
</div>
<div class="contact-form">
<div>
<h3 style="font-family: 'quicksandbold'; font-size:16px; color:#313131; padding-bottom:8px;">Dear Member</h3>
<span style="color:#D70000; font-size:16px; font-weight:bold;">We are sorry! Your last transaction was cancelled.</span>
</div>
</div>
</div><!-- /.container -->
Comments
Post a Comment