Recent Topics

Is it possible to integrate Razorpay Payment Gateway in Bagisto E-Commerce?



  • Hi,

    Please can anyone help me regarding the integration of razorpay, I have successfully installed razorpay payment gateway in bagisto ecommerce. But I am getting error while redirecting to razorpay payment after product place order. Please find below is the code for reference. Thank you.

    Controller.php

    <?php
    
    namespace Webkul\Razorpay\Http\Controllers;
    
    use Illuminate\Foundation\Bus\DispatchesJobs;
    use Illuminate\Routing\Controller as BaseController;
    use Illuminate\Foundation\Validation\ValidatesRequests;
    
    class Controller extends BaseController
    {
        use DispatchesJobs, ValidatesRequests;
    }
    
    

    StandardController.php

    <?php
    
    namespace Webkul\Razorpay\Http\Controllers;
    
    use Webkul\Checkout\Facades\Cart;
    use Webkul\Sales\Repositories\OrderRepository;
    use Webkul\Razorpay\Helpers\Ipn;
    
    /**
     * Paypal Standard controller
     *
     * @author    Jitendra Singh <[email protected]>
     * @copyright 2018 Webkul Software Pvt Ltd (http://www.webkul.com)
     */
    class StandardController extends Controller
    {
      public function __construct() {
          parent::__construct();
          $this->load->model('Site', 'site');
      }
      // index page
      public function index() {
          $data['title'] = 'Razorpay | TechArise';
          $data['productInfo'] = $this->site->getProduct();
          $this->load->view('razorpay/index', $data);
      }
    
      // checkout page
      public function checkout($id) {
          $data['title'] = 'Checkout payment | TechArise';
          $this->site->setProductID($id);
          $data['itemInfo'] = $this->site->getProductDetails();
          $data['return_url'] = site_url().'razorpay/callback';
          $data['surl'] = site_url().'razorpay/success';;
          $data['furl'] = site_url().'razorpay/failed';;
          $data['currency_code'] = 'INR';
          $this->load->view('razorpay/checkout', $data);
      }
    
      // initialized cURL Request
      private function get_curl_handle($payment_id, $amount)  {
          $url = 'https://api.razorpay.com/v1/payments/'.$payment_id.'/capture';
          $key_id = 'rzp_test_zF6hbss6pxUt6H';
          $key_secret = 'CxgEKsnqCJ8gwhiUnr4rixMY';
          $fields_string = "amount=$amount";
          //cURL Request
          $ch = curl_init();
          //set the url, number of POST vars, POST data
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_USERPWD, $key_id.':'.$key_secret);
          curl_setopt($ch, CURLOPT_TIMEOUT, 60);
          curl_setopt($ch, CURLOPT_POST, 1);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
          curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__).'/ca-bundle.crt');
          return $ch;
      }
    
      // callback method
      public function callback() {
          if (!empty($this->input->post('razorpay_payment_id')) && !empty($this->input->post('merchant_order_id'))) {
              $razorpay_payment_id = $this->input->post('razorpay_payment_id');
              $merchant_order_id = $this->input->post('merchant_order_id');
              $currency_code = 'INR';
              $amount = $this->input->post('merchant_total');
              $success = false;
              $error = '';
              try {
                  $ch = $this->get_curl_handle($razorpay_payment_id, $amount);
                  //execute post
                  $result = curl_exec($ch);
                  $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                  if ($result === false) {
                      $success = false;
                      $error = 'Curl error: '.curl_error($ch);
                  } else {
                      $response_array = json_decode($result, true);
                     // echo "<pre>";print_r($response_array);exit;
                          //Check success response
                          if ($http_status === 200 and isset($response_array['error']) === false) {
                              $success = true;
                          } else {
                              $success = false;
                              if (!empty($response_array['error']['code'])) {
                                  $error = $response_array['error']['code'].':'.$response_array['error']['description'];
                              } else {
                                  $error = 'RAZORPAY_ERROR:Invalid Response <br/>'.$result;
                              }
                          }
                  }
                  //close connection
                  curl_close($ch);
              } catch (Exception $e) {
                  $success = false;
                  $error = 'OPENCART_ERROR:Request to Razorpay Failed';
              }
              if ($success === true) {
                  if(!empty($this->session->userdata('ci_subscription_keys'))) {
                      $this->session->unset_userdata('ci_subscription_keys');
                   }
                  if (!$order_info['order_status_id']) {
                      redirect($this->input->post('merchant_surl_id'));
                  } else {
                      redirect($this->input->post('merchant_surl_id'));
                  }
    
              } else {
                  redirect($this->input->post('merchant_furl_id'));
              }
          } else {
              echo 'An error occured. Contact site administrator, please!';
          }
      }
      public function success() {
          $data['title'] = 'Razorpay Success | TechArise';
          $this->load->view('razorpay/success', $data);
      }
      public function failed() {
          $data['title'] = 'Razorpay Failed | TechArise';
          $this->load->view('razorpay/failed', $data);
      }
    }
    
    

    routes.php

    <?php
    
    Route::group(['middleware' => ['web']], function () {
        Route::prefix('razorpay/standard')->group(function () {
    
            Route::get('/redirect', 'Webkul\Razorpay\Http\Controllers\[email protected]')->name('razorpay.standard.redirect');
    
            Route::get('/success', 'Webkul\Razorpay\Http\Controllers\[email protected]')->name('razorpay.standard.success');
    
            Route::get('/cancel', 'Webkul\Razorpay\Http\Controllers\[email protected]')->name('razorpay.standard.cancel');
    
            Route::get('/ipn', 'Webkul\Razorpay\Http\Controllers\[email protected]')->name('razorpay.standard.ipn');
    
            Route::post('/ipn', 'Webkul\Razorpay\Http\Controllers\[email protected]')->name('razorpay.standard.ipn');
        });
    });
    
    

    standard-redirect.blade.php

    <?php $razorpayStandard = app('Webkul\Razorpay\Payment\Standard') ?>
    
    <body data-gr-c-s-loaded="true" cz-shortcut-listen="true">
        You will be redirected to the Razorpay website in a few seconds.
    
    
        <form action="{{ $razorpayStandard->getRazorpayUrl() }}" id="razorpay_standard_checkout" method="POST">
            <input value="Click here if you are not redirected within 10 seconds..." type="submit">
    
            @foreach ($razorpayStandard->getFormFields() as $name => $value)
    
                <input type="hidden" name="{{ $name }}" value="{{ $value }}">
    
            @endforeach
        </form>
    
        <script type="text/javascript">
            document.getElementById("razorpay_standard_checkout").submit();
        </script>
    </body>
    
    

    Payment/Razorpay.php

    <?php
    
    namespace Webkul\Razorpay\Payment;
    
    use Illuminate\Support\Facades\Config;
    use Webkul\Payment\Payment\Payment;
    
    /**
     * Paypal class
     *
     * @author    Jitendra Singh <[email protected]>
     * @copyright 2018 Webkul Software Pvt Ltd (http://www.webkul.com)
     */
    abstract class Razorpay extends Payment
    {
        /**
         * PayPal web URL generic getter
         *
         * @param array $params
         * @return string
         */
        public function getRazorpayUrl($params = [])
        {
            return sprintf('https://checkout.razorpay.com/v1/checkout.js',
                    $this->getConfigData('sandbox') ? 'sandbox.' : '',
                    $params ? '?' . http_build_query($params) : ''
                );
        }
    
        /**
         * Add order item fields
         *
         * @param array $fields
         * @param int $i
         * @return void
         */
        protected function addLineItemsFields(&$fields, $i = 1)
        {
            $cartItems = $this->getCartItems();
    
            foreach ($cartItems as $item) {
    
                foreach ($this->itemFieldsFormat as $modelField => $razorpayField) {
                    $fields[sprintf($razorpayField, $i)] = $item->{$modelField};
                }
    
                $i++;
            }
        }
    
        /**
         * Add billing address fields
         *
         * @param array $fields
         * @return void
         */
        protected function addAddressFields(&$fields)
        {
            $cart = $this->getCart();
    
            $billingAddress = $cart->billing_address;
    
            $fields = array_merge($fields, [
                'city'             => $billingAddress->city,
                'country'          => $billingAddress->country,
                'email'            => $billingAddress->email,
                'first_name'       => $billingAddress->first_name,
                'last_name'        => $billingAddress->last_name,
                'zip'              => $billingAddress->postcode,
                'state'            => $billingAddress->state,
                'address1'         => $billingAddress->address1,
                'address_override' => 1
            ]);
        }
    
        /**
         * Checks if line items enabled or not
         *
         * @param array $fields
         * @return void
         */
        public function getIsLineItemsEnabled()
        {
            return true;
        }
    }
    
    

    Payment/Standard.php

    <?php
    
    namespace Webkul\Razorpay\Payment;
    
    /**
     * Paypal Standard payment method class
     *
     * @author    Jitendra Singh <[email protected]>
     * @copyright 2018 Webkul Software Pvt Ltd (http://www.webkul.com)
     */
    class Standard extends Razorpay
    {
        /**
         * Payment method code
         *
         * @var string
         */
        protected $code  = 'razorpay_standard';
    
        /**
         * Line items fields mapping
         *
         * @var array
         */
        protected $itemFieldsFormat = [
            'id'       => 'item_number_%d',
            'name'     => 'item_name_%d',
            'quantity' => 'quantity_%d',
            'price'    => 'amount_%d',
        ];
    
        /**
         * Return paypal redirect url
         *
         * @var string
         */
        public function getRedirectUrl()
        {
            return route('razorpay.standard.redirect');
        }
    
        /**
         * Return form field array
         *
         * @return array
         */
        public function getFormFields()
        {
            $cart = $this->getCart();
    
            $fields = [
                'business'        => $this->getConfigData('business_account'),
                'invoice'         => $cart->id,
                'currency_code'   => $cart->cart_currency_code,
                'paymentaction'   => 'sale',
                'return'          => route('razorpay.standard.success'),
                'cancel_return'   => route('razorpay.standard.cancel'),
                'notify_url'      => route('razorpay.standard.ipn'),
                'charset'         => 'utf-8',
                'item_name'       => core()->getCurrentChannel()->name,
                'amount'          => $cart->sub_total,
                'tax'             => $cart->tax_total,
                'shipping'        => $cart->selected_shipping_rate->price,
                'discount_amount' => $cart->discount
            ];
    
            if ($this->getIsLineItemsEnabled()) {
                $fields = array_merge($fields, array(
                    'cmd'    => '_cart',
                    'upload' => 1,
                ));
    
                $this->addLineItemsFields($fields);
    
                $this->addShippingAsLineItems($fields, $cart->items()->count() + 1);
    
                if (isset($fields['tax'])) {
                    $fields['tax_cart'] = $fields['tax'];
                }
    
                if (isset($fields['discount_amount'])) {
                    $fields['discount_amount_cart'] = $fields['discount_amount'];
                }
            } else {
                $fields = array_merge($fields, array(
                    'cmd'           => '_ext-enter',
                    'redirect_cmd'  => '_xclick',
                ));
            }
    
            $this->addAddressFields($fields);
    
            return $fields;
        }
    
        /**
         * Add shipping as item
         *
         * @param array $fields
         * @param int $i
         * @return void
         */
        protected function addShippingAsLineItems(&$fields, $i)
        {
            $cart = $this->getCart();
    
            $fields[sprintf('item_number_%d', $i)] = $cart->selected_shipping_rate->carrier_title;
            $fields[sprintf('item_name_%d', $i)] = 'Shipping';
            $fields[sprintf('quantity_%d', $i)] = 1;
            $fields[sprintf('amount_%d', $i)] = $cart->selected_shipping_rate->price;
        }
    }
    
    


  • https://forums.bagisto.com/assets/uploads/files/1565077566209-screenshot-98.png

    There is no load property defined in Standard Controller that's why you getting Undefined Property Exception.

    https://forums.bagisto.com/assets/uploads/files/1565077547818-screenshot-100.png

    There is no need to call parent constructor, please remove the following line:

    parent::__construct();



  • Hii have you successfully integrate razorpay??

    if yes then reply



  • Hi @Pankaj,

    I didn't integrate razorpay Payment Gateway because I am getting error at the time of redirection. So, I have integrated Instamojo Payment Gateway.



  • okk @Keerthi

    Thanks for reply



  • Hi @Pankaj,

    Have you integrated Razorpay Payment Gateway in bagisto e-commerce?



  • Hi,

    I am getting error like "404 page not found" with live mode of razorpay URL at the time of redirecting to the payment gateway. Can anyone please suggest me, thank you



  • Hi @Keerthi

    Kindly check your redirection URL at time of checkout whether it is right or wrong & make sure that you are redirecting to your redirection(Where Razorpay URL is mentioned) page after click Place order button.

    Thanks



  • Hi @Keerthi

    yes i have integrated Razorpay payment gateway by creating new package



  • Hi @Keerthi , can you tell me you have integrated razorpay payment gateway integration. i have done same steps what ever you have done. i have cloned paypal package and every where renamed it with razor pay its not showing any error but razorpay option is not coming on checkout page
    ![alt text](Capture.PNG image url)



  • @Jitendra

    Hi jitendra,

    i have added razorpay payment gateway but here the error is comming after selecting the razorpay payment can not call to the constructor, if i m removing the
    line of parent::__construct(); then again error is comming like
    Undefined property: Webkul\Razorpay\Http\Controllers\StandardController::$load

    please help me.

    Thankyou



  • @Pankaj
    Hi pankaj can you tell me how to integrate razorpay payment gateway in the bagisto, i m getting a error when our page is redirecting on payment page after selecting razor pay,
    i m sharing you screen shot then you can better understand

    483c312b-3294-438c-8061-2ec70b1b2afa-image.png
    b73282e9-299e-4f87-a0b6-b5f01e27c763-image.png

    Please help me,
    Thanks



  • Try to to check what you are getting in the post to do so, write dd(request()->all()); in your code.


Log in to reply