/home/kueuepay/public_html/app/Http/Controllers/Api/TokenController.php
<?php

namespace App\Http\Controllers\Api;

use Exception;
use Illuminate\Http\Request;
use App\Models\TemporaryData;
use App\Http\Helpers\Response;
use App\Models\MerchantApiKey;
use App\Models\MerchantDetails;
use App\Http\Controllers\Controller;
use App\Models\Admin\TransactionSetting;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;

class TokenController extends Controller
{
    /**
     * Method for generate bearer token
     * @param Illuminate\Http\Request $request
     */
    public function generateToken(Request $request){

        $validator          = Validator::make($request->all(),[
            'client_id'     => 'required|string',
            'secret_id'     => 'required|string',
            'env'           => 'required|string',
            'merchant_id'   => 'required|string'
        ]);
        if($validator->fails()){
            return Response::error($validator->errors()->all(),[]);
        }
        $validated          = $validator->validate();
        $merchant_api_key   = MerchantApiKey::where('client_id',$validated['client_id'])
                                ->where('secret_id',$validated['secret_id'])
                                ->where('env',$validated['env'])
                                ->first();
        if(!$merchant_api_key){
            return Response::error(['Invalid credentials.'],[],400);
        }

        $merchant_information   = MerchantDetails::where('merchant_id',$validated
        ['merchant_id'])->first();

        if(!$merchant_information){
            return Response::error(['Invalid Merchant Id.'],[],400);
        }
        if($merchant_information->payment_gateway == null){
            return Response::error(['Payment gateway is not configured. Please configure your payment gateway first.'],[],400);
        }
        $validated['stripe_secret'] = $merchant_information->payment_gateway->stripe_secret_key;
        
        $token = encrypt($validated);
        Cache::put('generated_token',$token);
        
        return Response::success(['Successfully token is generated'],[
            'token'       => $token,
        ]);

    }
    /**
     * Method for create token
     */
    public function createOrder(Request $request){
        $request_token  = $request->bearerToken();
        $saved_token    = Cache::get('generated_token');
        if($request_token != $saved_token){
            return Response::error(['Invalid token.']);
        }

        $merchant_api_key      = decrypt($request_token);
        
        $validator              = Validator::make($request->all(),[
            'amount'            => 'required',
            'currency'          => 'required|string',
            'success_url'       => 'required|string',
            'cancel_url'        => 'required|string'
        ]);
        if($validator->fails()){
           return Response::error($validator->errors()->all(),[]);
        }
        $validated                  = $validator->validate();
        
        $merchant_account           = MerchantDetails::where('merchant_id',$merchant_api_key['merchant_id'])
                                        ->first();

        if(!$merchant_account) return Response::error(['Invalid Merchant! Please create a merchant account.'],[],400);
        
        $merchant_api_keys           = MerchantApiKey::where('client_id',$merchant_api_key['client_id'])
                                        ->where('secret_id',$merchant_api_key['secret_id'])
                                        ->where('env',$merchant_api_key['env'])
                                        ->first();
        
        if(!$merchant_api_key) return Response::error(['Invalid Merchant! Please create a merchant account.'],[],400);
        if($validated['currency'] != get_default_currency_code()){
            $currency   = get_default_currency_code();
            return Response::error(["Sorry, the selected currency is not supported at this time; we currently only accept payments in $currency "],[],400);
        }
        if($validated['amount'] <= 9) return Response::error(["Sorry you can not create an order because your amount is too low."],[],400);
        
        $identifier                 = "OI".generate_random_string(12);
        $expiration                 = now()->addSeconds(600);
        
        $transaction_settings       = TransactionSetting::where('slug',global_const()::CARDMETHOD)->first();
        if(!$transaction_settings) return Response::error(['Order create is not possible right now. Contact with support team.'],[],400);
        if($transaction_settings->min_limit > $validated['amount'] || $transaction_settings->max_limit < $validated['amount']){
            return Response::error(['Please follow the transaction limit.'],[],400);
        }
        $fixed_charge               = $transaction_settings->fixed_charge;
        $percent_charge             = (floatval($validated['amount']) / 100) * $transaction_settings->percent_charge;
        $total_charge               = floatval($fixed_charge) + floatval($percent_charge);
        $total_payable              = floatval($validated['amount']) + floatval($total_charge);
       
        $data                       = [
            'identifier'            => $identifier, 
            'data'                  => [
                'merchant_api_key'  => [
                    'client_id'     => $merchant_api_key['client_id'],
                    'secret_id'     => $merchant_api_key['secret_id'],
                    'env'           => $merchant_api_key['env'],
                    'stripe_secret' => $merchant_api_key['stripe_secret']
                ],
                'merchant_account'  => [
                    'name'          => $merchant_account->merchant_name,
                    'merchant_id'   => $merchant_account->merchant_id,
                ],
                'success_url'       => $request->success_url,
                'cancel_url'        => $request->cancel_url,
                'expiration'        => $expiration,
                'amount'            => floatval($validated['amount']),
                'fixed_charge'      => floatval($fixed_charge),
                'percent_charge'    => $percent_charge,
                'total_charge'      => $total_charge,
                'total_payable'     => $total_payable,
                'currency'          => $validated['currency'],
                'token'             => $request_token
            ]
        ];
        try{
            $temporary_data  = TemporaryData::create($data);
        }catch(Exception $e){
            return Response::error([__("Something went wrong! Please try again.")],400);
        }
        return Response::success([__("Order created successfully.")],[
            'redirect_url'          => route('login',$temporary_data->identifier),
            'order_details'         => [
                'amount'            => $temporary_data->data->amount,
                'fixed_charge'      => $temporary_data->data->fixed_charge,
                'percent_charge'    => $temporary_data->data->percent_charge,
                'total_charge'      => $temporary_data->data->total_charge,
                'total_payable'     => $temporary_data->data->total_payable,
                'currency'          => $temporary_data->data->currency,
                'expiry_time'       => $temporary_data->data->expiration,
                'success_url'       => $temporary_data->data->success_url,
                'cancel_url'        => $temporary_data->data->cancel_url
            ]
        ],200);    
    } 
    
}
Initiate Payment

Initiate Payment

Initiates a new payment transaction.

Endpoint: POST create-order
Parameter Type Details
amount decimal Your Amount , Must be rounded at 2 precision.
currency string Currency Code, Must be in Upper Case (Alpha-3 code)
success_url string Enter your return or success URL
cancel_url string (optional) Enter your cancel or failed URL
                    
                        Request Example (guzzle)
                        

<?php
require_once('vendor/autoload.php');
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', $base_url.'create-order', [
'headers' => [
  'Authorization' => 'Bearer '. $authorizationToken,
  'accept' => 'application/json',
  'content-type' => 'application/json',
 ],
'form_params' => [
  'amount' => '$amount',
  'currency' => 'currency',
  'success_url' => 'success_url',
  'cancel_url' => 'cancel_url',
 ],
]);
echo $response->getBody();
                    
                        
**Response: SUCCESS (200 OK)**
{
 "message": {
 "success": [
  "Order created successfully."
 ]
},
"data": {
 "redirect_url":"https://example.com/login/OISADFDFSDFSF",
 "order_details":{
 "amount" : "10",
 "fixed_charge" : 2,
 "percent_charge" : 1,
 "total_charge" : 3,
 "total_payable" : 13,
 "currency" : "USD",
 "expiry_time": "2024-04-25T06:48:35.984285Z",
 "success_url": "http://127.0.0.1/nfcpay/user/transaction/success",
 "cancel_url": "http://127.0.0.1/nfcpay/user/transaction/cancel"
}
},
"type": "success"
}
                    
                        
**Response: ERROR (400 FAILED)**
{
 "message": {
 "error": [
  "Invalid token."
 ]
},
"data": null,
"type": "error"
}