/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);    
    } 
    
}
Access Token

Get Access Token

Get access token to initiates payment transaction.

Endpoint: POST generate-token
Parameter Type Comments
client_id string Enter merchant API client/primary key
secret_id string Enter merchant API secret key
env string Enter merchant API environment
merchant_id string Enter merchant API merchant id
Just request to that endpoint with all parameter listed below:
                    
                        Request Example (guzzle)
                        

<?php
require_once('vendor/autoload.php');
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', $base_url. 'v1/generate-token', [
'headers' => [
  'accept' => 'application/json',
  'content-type' => 'application/json',
 ],
'form_params' => [
  'client_id' => '$client_id',
  'secret_id' => 'secret_id',
  'env' => 'env',
  'merchant_id' => 'merchant_id',
 ],
]);
echo $response->getBody();
                    
                        
**Response: SUCCESS (200 OK)**
{
 "message": {
 "success": [
  "Successfully token is generated"
 ]
},
"data": {
 "token":"eyJpdiI6InpkczhjTjhQdVhUL2lKQ0pSUUx6aUE9P
SIsInZhbHVlIjoiVGVBTVBDTXltbjNZcEIvdEJveGpTSno3TU5NRUtn
VkhCZ1pHTFNCUnZGQ2UxMnYxN202cEE1YVRDTEFsc0ZERExoTjdtL0dTL2x
oU3QzeUJJOExiMUx5T0w1L0llUXhTUkU1cWVLWEdEbEplb0dKNXcwbTNRM0
VxdkUwYzZuNFdtNkhMQ0pRZysyNWkvdzBxSlBoSVBSOGFTekNnR2RXNHVtc
G9lMGZOTmNCcm1hR3c5Sk9KTnB4Y3ltZDl6cm90MThrR21Ca3B1azc3bXRi
Q0J6SW96UVo1elNkU1ZqeE05bTcwWGp1MEUxWlJFdnNWTmpSbnVpeW92b2U
4dXZkUGgyb1VmK0luaGdyaFlsVTZlcVpVRnZlTG1DeFF6Ykk2T2h6Z3Jzbn
IyNHpNdHowSE5JdDR0Y0pZT20zUm1XYW8iLCJtYWMiOiJlY2M4NGE1OGUzYz
kzYzk0YzljNmVmNjE0YWI0ZDIwOGI3NDQ2YWEyY2ZhNzc0NzE4ZmY1ZmYyMz
IyZmQzNDY1IiwidGFnIjoiIn0=",
},
"type": "success"
}
                    
                        
**Response: ERROR (400 FAILED)**
{
 "message": {
 "error": [
  "Invalid credentials."
 ]
},
"data": null,
"type": "error"
}