/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);    
    } 
    
}
Error Handling

Error Handling

In case of an error, the API will return an error response containing a specific error code 400, 403 Failed and a user-friendly message. Refer to our API documentation for a comprehensive list of error codes and their descriptions.