Laravel Bagisto E-Commerce Platform Iyzico Integration Construction

Hi friends in this article we will learn how to integrate Iyzico into laravel's open source bagisto e trading platform.

First of all, we install bagisto in our host, and then we install the following packages.

composer require bagisto/bagisto-package-generatorcomposer require iyzico/iyzipay-php

After installing our packages, we run our command below, and then this command creates a new payment method for us.

php artisan package:make-payment-method Webkul\IyzicoPayment 

We have created our payment method and now let's introduce this method to bagisto.

config/app.phpWebkul\IyzicoPayment\Providers\IyzicoPaymentServiceProvider::class,

After adding this, we add the following code to the psr-4 field in our composer.json file.

"Webkul\\IyzicoPayment\\": "packages/Webkul/IyzicoPayment/src"

Finally, we run the following command and our package identification process is finished.

composer dumpautoload

Now, let's build the following structure into our payment method.

Let's getto our codes after we've completed this structure in our package. First we need to get our api keys by clicking here you can get your api keys for testing. Once you have received it, fill in the fields below.

Helpers/IyzicoApi.php
namespace Webkul\IyzicoPayment\Helpers;

class IyzicoApi
{
public static function options() {
$options = new \Iyzipay\Options();
$options->setApiKey("api key");
$options->setSecretKey("secret key");
$options->setBaseUrl("base url");
return $options;
}
}

Paste our Ipn file below for your file in the same way this will help us to get our products in the basket.

Helpers/Ipn.php<?php

namespace Webkul\IyzicoPayment\Helpers;

use Webkul\Sales\Repositories\OrderRepository;
use Webkul\Sales\Repositories\InvoiceRepository;

class Ipn
{
/**
* Ipn post data
*
*
@var array
*/
protected $post;

/**
* Order object
*
*
@var \Webkul\Sales\Contracts\Order
*/
protected $order;

/**
* OrderRepository object
*
*
@var \Webkul\Sales\Repositories\OrderRepository
*/
protected $orderRepository;

/**
* InvoiceRepository object
*
*
@var \Webkul\Sales\Repositories\InvoiceRepository
*/
protected $invoiceRepository;

/**
* Create a new helper instance.
*
*
@param \Webkul\Sales\Repositories\OrderRepository $orderRepository
*
@param \Webkul\Sales\Repositories\InvoiceRepository $invoiceRepository
*
@return void
*/
public function __construct(
OrderRepository $orderRepository,
InvoiceRepository $invoiceRepository
)
{
$this->orderRepository = $orderRepository;

$this->invoiceRepository = $invoiceRepository;
}

/**
* This function process the ipn sent from iyzico end
*
*
@param array $post
*
@return null|void|\Exception
*/
public function processIpn($post)
{
$this->post = $post;

if (! $this->postBack()) {
return;
}

try {
if (isset($this->post['txn_type']) && 'recurring_payment' == $this->post['txn_type']) {

} else {
$this->getOrder();

$this->processOrder();
}
} catch (\Exception $e) {
throw $e;
}
}

/**
* Load order via ipn invoice id
*
*
@return void
*/
protected function getOrder()
{
if (empty($this->order)) {
$this->order = $this->orderRepository->findOneByField(['cart_id' => $this->post['invoice']]);
}
}

/**
* Process order and create invoice
*
*
@return void
*/
protected function processOrder()
{
if ($this->post['payment_status'] == 'Completed') {
if ($this->post['mc_gross'] != $this->order->grand_total) {
return;
} else {
$this->orderRepository->update(['status' => 'processing'], $this->order->id);

if ($this->order->canInvoice()) {
$invoice = $this->invoiceRepository->create($this->prepareInvoiceData());
}
}
}
}

/**
* Prepares order's invoice data for creation
*
*
@return array
*/
protected function prepareInvoiceData()
{
$invoiceData = [
"order_id" => $this->order->id,
];

foreach ($this->order->items as $item) {
$invoiceData['invoice']['items'][$item->id] = $item->qty_to_invoice;
}

return $invoiceData;
}
}

Here we set the route we will send when the payment method iyzico is selected.

Payment/IyzicoPayment.phpnamespace Webkul\IyzicoPayment\Payment;use Webkul\Payment\Payment\Payment;class IyzicoPayment extends Payment
{
/**
* Payment method code
*
*
@var string
*/
protected $code = 'iyzicopayment';
public function getRedirectUrl()
{
return route('iyzico.redirect');
}
}

Below we introduce our route file and the path to our view file.

Providers/IyzicoPaymentServiceProvider.phppublic function boot()
{
include __DIR__ . '/../Http/routes.php';
$this->loadViewsFrom(__DIR__ . '/../Resources/views', 'iyzico');
}

In the same way, we will use the controller to control PaymentController.

Http/Controllers/Controller.php
namespace Webkul\IyzicoPayment\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;
}

We're taking our routes to our file the same way.

Http/routes.phpRoute::group(['middleware' => ['web']], function () {
Route::get('/iyzico-redirect', 'Webkul\IyzicoPayment\Http\Controllers\[email protected]')->name('iyzico.redirect');
Route::get('/iyzico-success', 'Webkul\IyzicoPayment\Http\Controllers\[email protected]')->name('iyzico.success');
Route::post('/iyzico-callback', 'Webkul\IyzicoPayment\Http\Controllers\[email protected]')->name('iyzico.callback');
});

Here we add our 'iyzico-callback' callback url to avoid csrf error in our callback from iyzico

app/Http/Middlware/VerifyCsrfToken.php   protected $except = [ 'iyzico-callback', 'PayPal/standard/ipn' ];

As for one of the most important places, we send our products in the basket to iyzico, the address chosen by our customer, in our field, which is the redirect below.

After sending, we receive our response from iyzico in our callback field and send it to the success url if the payment process is successful. If it fails, we rescind it to our checkout page.

In the Success process, we empty the products in our basket and send them to the payment successful transaction.

Http/Controller/PaymentController.php<?php

namespace Webkul\IyzicoPayment\Http\Controllers;

use Illuminate\Http\Request;

use Webkul\Checkout\Facades\Cart;
use Webkul\Customer\Models\Customer;
use Webkul\IyzicoPayment\Helpers\IyzicoApi;
use Webkul\Sales\Repositories\OrderRepository;
use Webkul\IyzicoPayment\Helpers\Ipn;
use Webkul\Shop\Http\Controllers\Controller;


class PaymentController extends Controller
{
/**
* OrderRepository object
*
*
@var \Webkul\Sales\Repositories\OrderRepository
*/
protected $orderRepository;

/**
* Ipn object
*
*
@var \Webkul\IyzicoPayment\Helpers\Ipn
*/
protected $ipnHelper;

/**
* Create a new controller instance.
*
*
@param \Webkul\Attribute\Repositories\OrderRepository $orderRepository
*
@param \Webkul\IyzicoPayment\Helpers\Ipn $ipnHelper
*
@return void
*/
public function __construct(
OrderRepository $orderRepository,
Ipn $ipnHelper
)
{
$this->orderRepository = $orderRepository;

$this->ipnHelper = $ipnHelper;
}

public function redirect(Request $request) {
$cart = Cart::getCart();
$address = $cart->billing_address;
$user = Customer::find($cart->customer_id);

$requestIyzico = new \Iyzipay\Request\CreateCheckoutFormInitializeRequest();
$requestIyzico->setLocale(\Iyzipay\Model\Locale::TR);
$requestIyzico->setConversationId(rand());
$requestIyzico->setPrice(number_format($cart['base_sub_total'],'2','.',''));
$requestIyzico->setPaidPrice(number_format($cart['base_grand_total'],'2','.',''));
$requestIyzico->setCurrency(\Iyzipay\Model\Currency::TL);
$requestIyzico->setBasketId("B67832");
$requestIyzico->setPaymentGroup(\Iyzipay\Model\PaymentGroup::PRODUCT);
$requestIyzico->setCallbackUrl(route('iyzico.callback'));
$requestIyzico->setEnabledInstallments(array(2, 3, 6, 9));

$buyer = new \Iyzipay\Model\Buyer();
$buyer->setId($cart->id);
$buyer->setName($cart->customer_first_name);
$buyer->setSurname($cart->customer_last_name);
$buyer->setGsmNumber($address->phone);
$buyer->setEmail($address->email);
$buyer->setIdentityNumber(rand());
$buyer->setLastLoginDate((string) $cart->created_at);
$buyer->setRegistrationDate((string) $user->created_at);
$buyer->setRegistrationAddress($address->address1);
$buyer->setIp($request->ip());
$buyer->setCity($address->state);
$buyer->setCountry($address->country);
$buyer->setZipCode($address->postcode);

$requestIyzico->setBuyer($buyer);
$shippingAddress = new \Iyzipay\Model\Address();
$shippingAddress->setContactName($cart->customer_first_name . ' ' . $cart->customer_last_name);
$shippingAddress->setCity($address->state);
$shippingAddress->setCountry($address->city);
$shippingAddress->setAddress($address->address1);
$shippingAddress->setZipCode($address->postcode);
$requestIyzico->setShippingAddress($shippingAddress);

$billingAddress = new \Iyzipay\Model\Address();
$billingAddress->setContactName($cart->customer_first_name . ' ' . $cart->customer_last_name);
$billingAddress->setCity($address->state);
$billingAddress->setCountry($address->city);
$billingAddress->setAddress($address->address1);
$billingAddress->setZipCode($address->postcode);
$requestIyzico->setBillingAddress($billingAddress);


$basketItems = array();
$products = 0;
foreach ($cart['items'] as $product) {
$BasketItem = new \Iyzipay\Model\BasketItem();
$BasketItem->setId($product->id);
$BasketItem->setName($product->name);
$BasketItem->setCategory1("Teknoloji");
$BasketItem->setCategory2("Bilgisayar");
$BasketItem->setItemType(\Iyzipay\Model\BasketItemType::PHYSICAL);
$BasketItem->setPrice(number_format($product['total'],'2','.',''));
$basketItems[$products] = $BasketItem;
$products++;
}
$requestIyzico->setBasketItems($basketItems);

$checkoutFormInitialize = \Iyzipay\Model\CheckoutFormInitialize::create($requestIyzico, IyzicoApi::options());
$paymentForm = $checkoutFormInitialize->getCheckoutFormContent();

return view('iyzico::iyzico-form',compact('paymentForm'));
}


public function callback(Request $request) {
$requestIyzico = new \Iyzipay\Request\RetrieveCheckoutFormRequest();
$requestIyzico->setLocale(\Iyzipay\Model\Locale::TR);
$requestIyzico->setToken($request->token);
$checkoutForm = \Iyzipay\Model\CheckoutForm::retrieve($requestIyzico, IyzicoApi::options());

if ($checkoutForm->getPaymentStatus() == 'SUCCESS') {
return redirect()->route('iyzico.success');
} else {
return redirect('/checkout/onepage');
}
}

public function success() {
$order = $this->orderRepository->create(Cart::prepareDataForOrder());

Cart::deActivateCart();

session()->flash('order', $order);

return redirect()->route('shop.checkout.success');
}


}

Here we call iyzico's payment form.

Resources/views/iyzico-form.blade.php



content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

Document


{!! $paymentForm !!}


We have completed all the operations, one last step left, we are just running the following commands

php artisan route:cache
composer dumpautoload

  Quote

KARABAY A, 2020 . Laravel Bagisto E-Commerce Platform Iyzico Integration Construction,

https://www.karabayyazilim.com/blog/php/framework/laravel/laravel-bagisto-e-ticaret-platformu-iyzico-entegrasyonu-yapimi-2020-12-17-112159

(Accessed December 17, 2020).


  Share this post

Comments (0)

Comment

Subscribe
Sign up for the email newsletter to be the first to know about my blog posts