Skip to content

Instantly share code, notes, and snippets.

@Miri92
Created August 9, 2020 07:56
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save Miri92/758d1a3bccffd003fdde09c3c752b5e4 to your computer and use it in GitHub Desktop.
Save Miri92/758d1a3bccffd003fdde09c3c752b5e4 to your computer and use it in GitHub Desktop.
KapitalBank Payment API with PHP Laravel framework - Example snippet
<?php
namespace App\Models;
use App\Database\EloquentModel as Model;
class Payment extends Model
{
protected $fillable = ['order_id', 'session_id', 'currency', 'order_status', 'order_description', 'amount', 'payment_url', 'status_code','order_check_status','language_code'];
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\{ Payment };
use Illuminate\Support\Facades\{DB, File, Hash, Storage, Validator, Config, Auth, Mail};
use SimpleXMLElement;
use App\Traits\Log;
class PaymentKapitalController extends Controller
{
protected $serviceUrl = 'https://e-commerce.kapitalbank.az:5443/Exec';
protected $cert = "kapitalbank_certificates/templ.crt";
protected $key = "kapitalbank_certificates/merchant_name2.key";
protected $merchant_id = 'E1000010';
protected $language = 'RU';
const PORT = 5443;
public function __construct()
{
if (Storage::disk('local')->exists($this->cert)) {
$this->cert = storage_path('app/'.$this->cert);
} else {
throw new \Exception("Certificate does not exists: $this->cert");
}
if (Storage::disk('local')->exists($this->key)) {
$this->key = storage_path('app/'.$this->key);
} else {
throw new \Exception("Key does not exists: $this->key");
}
}
public function index(){
return 'index';
}
public function curl($xml){
$url = $this->serviceUrl;
$ch = curl_init();
curl_setopt($ch, CURLOPT_PORT, self::PORT);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSLCERT, $this->cert);
curl_setopt($ch, CURLOPT_SSLKEY, $this->key);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//Error handling and return result
$data = curl_exec($ch);
if ($data === false) {
$result = curl_error($ch);
} else {
$result = $data;
}
// Close handle
curl_close($ch);
return $result;
}
public function createTestOrder(){
//echo header("Location: ");
$order_data = array(
'merchant' => $this->merchant_id,
'amount' => 1,
'currency' => 944,
'description' => 'Templateplanet Purchase',
'lang' => 'RU'
);
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<TKKPG>
<Request>
<Operation>CreateOrder</Operation>
<Language>'.$order_data['lang'].'</Language>
<Order>
<OrderType>Purchase</OrderType>
<Merchant>'.$order_data['merchant'].'</Merchant>
<Amount>'.$order_data['amount'].'</Amount>
<Currency>'.$order_data['currency'].'</Currency>
<Description>'.$order_data['description'].'</Description>
<ApproveURL>https://templateplanet.az/en/kapital/approve</ApproveURL>
<CancelURL>https://templateplanet.az/en/kapital/cancel</CancelURL>
<DeclineURL>https://templateplanet.az/en/kapital/decline</DeclineURL>
</Order>
</Request>
</TKKPG>
';
//return $xml;
$result = $this->curl($xml);
return $this->handleCurlResponse($order_data,$result);
//dd($result);
// $result;
}
public function handleCurlResponse($inital_data, $data){
$oXML = new SimpleXMLElement($data);
//dd($oXML);
$OrderID = $oXML->Response->Order->OrderID;
$SessionID = $oXML->Response->Order->SessionID;
$paymentBaseUrl = $oXML->Response->Order->URL;
Payment::create([
'amount' => $inital_data['amount'],
'order_id' => $OrderID,
'session_id' => $SessionID,
'payment_url' => $paymentBaseUrl,
'staus_code' => $oXML->Response->Status,
'order_description' => $inital_data['description'],
'currency' => $inital_data['currency'],
'language_code' => $inital_data['currency'],
]);
///
$redirectUrl = $paymentBaseUrl."?ORDERID=".$OrderID."&SESSIONID=".$SessionID."&";
//dd($redirectUrl);
//echo $redirectUrl;
return redirect()->to($redirectUrl);;
//return header("Location: ");
}
public function approveUrl(Request $request){
Log::write('approveUrl','kapitalBank',$request->all());
$xmlmsg = new SimpleXMLElement($request->xmlmsg);
$getPaymentRow = Payment::where('order_id', '=', $xmlmsg->OrderID)->first();
if($getPaymentRow){
$getPaymentRow->update([
'order_status' => $xmlmsg->OrderStatus,
]);
$this->getOrderStatus($getPaymentRow);
}
return 'approve';
}
public function cancelUrl(Request $request){
//echo $request->xmlmsg;
$xmlmsg = new SimpleXMLElement($request->xmlmsg);
Log::write('cancelUrl','kapitalBank',$request->all());
$getPaymentRow = Payment::where('order_id', '=', $xmlmsg->OrderID)->first();
if($getPaymentRow){
$getPaymentRow->update([
'order_status' => $xmlmsg->OrderStatus,
]);
}
return 'cancel';
}
public function declineUrl(Request $request){
//dd($request->all());
Log::write('declineUrl','kapitalBank',$request->all());
if ($request->filled('xmlmsg')){
$xmlmsg = new SimpleXMLElement($request->xmlmsg);
//dd($xmlmsg->OrderStatus);
$getPaymentRow = Payment::where('order_id', '=', $xmlmsg->OrderID)->first();
if($getPaymentRow){
$getPaymentRow->update([
'order_status' => $xmlmsg->OrderStatus,
]);
}
}
return 'DECLINED';
}
//Internet shop must perform the Get Order Status operation for the security purposes and decide whether to provide the service or not depending on the response.
public function getOrderStatus($data){
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<TKKPG>
<Request>
<Operation>GetOrderStatus</Operation>
<Language>'.$this->language.'</Language>
<Order>
<Merchant>'.$this->merchant_id.'</Merchant>
<OrderID>'.$data->order_id.'</OrderID>
</Order>
<SessionID>'.$data->session_id.'</SessionID>
</Request>
</TKKPG>';
$response = $this->curl($xml);
$xmlmsg = new SimpleXMLElement($response);
//dd($xmlmsg->Response->Status);
$getPaymentRow = Payment::where('order_id', '=', $xmlmsg->Response->Order->OrderID)->first();
if($getPaymentRow){
$getPaymentRow->update([
'order_check_status' => $xmlmsg->Response->Order->OrderStatus,
'status_code' => $xmlmsg->Response->Status,
]);
}
return $response;
}
//paymentLogs in admin
public function paymentLogs(){
$rows = Payment::latest()->paginate(20);
return view('back.settings.payment_logs', compact('rows'));
}
}
@jonayeidk
Copy link

where is you log file?

@jonayeidk
Copy link

what you check on traits\Log file ??

@DarkcoderSe
Copy link

Thanks @Miri92. I've tested it and it is working.

@Miri92
Copy link
Author

Miri92 commented Jan 17, 2021

what you check on traits\Log file ??

<?php

namespace App\Traits;

use Illuminate\Support\Facades\Storage;

Class Log
{

  static function write($filename, $foldername, $content){
        $logDate = date('d-M-Y');
        $logTime = date('H-i-s');
        $logFile = $filename.'-'.$logDate.'.log';
        $logText = '*** '.$logTime.' '.$logDate.' ***'."\r\n";

        if (is_array($content)) {
            $logText .= 'Array - '."\r\n";
            foreach ($content as $key => $value) {
                $logText .= $key.': '.json_encode($value)."\r\n";
            }
        } elseif (is_string($content)) {
            $logText .= 'String - '."\r\n";
            $logText .= $content."\r\n";

        } else {
            $content = json_encode($content);
            $logText .= 'Other - '."\r\n";
            $logText .= $content."\r\n";
        }
        $logText .= "============================================="."\r\n";

        //storage/app/azericard
        return Storage::append($foldername.'/'.$logFile,$logText);
    }
}

@Miri92
Copy link
Author

Miri92 commented Jan 17, 2021

Thanks @Miri92. I've tested it and it is working.

You are welcome.

@jonayeidk
Copy link

jonayeidk commented Feb 17, 2021

Can you please write a document how the process going , i am facing issue on curl function , i am getting this error ->
"error:14094416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown"

@Miri92
Copy link
Author

Miri92 commented Feb 21, 2021

Can you please write a document how the process going , i am facing issue on curl function , i am getting this error ->
"error:14094416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown"

the bank have to send you documentation about generating certificate process.

@jonayeidk
Copy link

Can you please write a document how the process going , i am facing issue on curl function , i am getting this error ->
"error:14094416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown"

the bank have to send you documentation about generating certificate process.

yes i got it and its working , but how to do i refund system can you please give me the refund function for it?

@Miri92
Copy link
Author

Miri92 commented Mar 4, 2021

Can you please write a document how the process going , i am facing issue on curl function , i am getting this error ->
"error:14094416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown"

the bank have to send you documentation about generating certificate process.

yes i got it and its working , but how to do i refund system can you please give me the refund function for it?

There was not refund issue in documentation, which they send me. You might contact with the bank about this issue.

@jonayeidk
Copy link

jonayeidk commented Mar 5, 2021 via email

@VusalGhasanov
Copy link

Can you please write a document how the process going , i am facing issue on curl function , i am getting this error ->
"error:14094416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown"

You need to get certificate for fix this error

@DarkcoderSe
Copy link

It destroy the session in chrome browser but working perfect in firefox. I have wrote the htaccess ans set-cookie sameSite = null. but the issue persist. Any solution?

@Miri92
Copy link
Author

Miri92 commented Mar 25, 2021

It destroy the session in chrome browser but working perfect in firefox. I have wrote the htaccess ans set-cookie sameSite = null. but the issue persist. Any solution?

Also there is config/session.php file.
It is strange issue, I faced this issue in other payment api, but I could't fix it. Only this simple solution helped me.

//use it in your callback method
if (!Auth::check()){
      Auth::login($this->transaction->user);
 }

@DarkcoderSe
Copy link

It destroy the session in chrome browser but working perfect in firefox. I have wrote the htaccess ans set-cookie sameSite = null. but the issue persist. Any solution?

Also there is config/session.php file.
It is strange issue, I faced this issue in other payment api, but I could't fix it. Only this simple solution helped me.

//use it in your callback method
if (!Auth::check()){
      Auth::login($this->transaction->user);
 }

That's not the ideal solution. But, it do the trick. Thanks!

@nihat-js
Copy link

nihat-js commented Apr 3, 2021

salam kapitalbankdan basqa azerbaycanda hansi banklar elektron odemeni temin edir?

@Miri92
Copy link
Author

Miri92 commented Apr 5, 2021

salam kapitalbankdan basqa azerbaycanda hansi banklar elektron odemeni temin edir?

PashaBank, BeynalxalqBank. Diger bir necesi de olmalidir hansi ki Azericard, MilliKart kimi sistemler vasitesile teminat verirler.

@jonayeidk
Copy link

Failed to connect to e-commerce.kapitalbank.az port 5443: No route to host ! why it happened ? please

@al1yew
Copy link

al1yew commented Jan 19, 2023

Salam, men pg.kapitalbank documentation-dan postmana mene gonderilen .crt fayli elave edirem. Mennen hele .key fayl istenilir. Onu generate etdiyim CSR icinde tapdim. Copy etdim .txt fayla, extentionunu deyishdim etdim .key

Elave etdim postmana, mene eyni erroru verir sorgu gonderende. Error: write EPROTO 64359432:error:10000412:SSL routines:OPENSSL_internal:SSLV3_ALERT_BAD_CERTIFICATE:../../../../src/third_party/boringssl/src/ssl/tls_record.cc:594:SSL alert number 42

Metod Get, post yoxlamisham, URL da ki hamsini yoxlamisham, hem documentationdaki, hemde sizin PHP kodunuzdaki. Her cure kombinaciya etdim. Postman eyni erroru verir. Bankin emekdashi ile elaqe gurdum mail ile, gec ve cox qisa cavab verir deye tam olarag basha dushmurem. Xahish edirem belke siz bilersiz ne etmek lazimdir. Emaile screenshotlar da gonderdim, mene voobshe dediler ki Settings-de host-u documentationdaki kimi yox, bashqa cur yazim...

@al1yew
Copy link

al1yew commented Jan 19, 2023

Ve umumiyyetle, bank olmayan payment API var mi olkede? Millikart eshitmishem, Payriff, vessalam. Teshekkur

@al1yew
Copy link

al1yew commented Jan 26, 2023

problem bankda idi)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment