/home/kueuepay/www/app/Http/Controllers/User/AuthorizationController.php
<?php

namespace App\Http\Controllers\User;

use Exception;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Constants\GlobalConst;
use App\Models\UserAuthorization;
use App\Http\Controllers\Controller;
use App\Traits\ControlDynamicInputFields;
use App\Providers\Admin\BasicSettingsProvider;
use Illuminate\Validation\ValidationException;
use App\Notifications\User\Auth\SendAuthorizationCode;

class AuthorizationController extends Controller
{
    use ControlDynamicInputFields;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function showMailFrom($token)
    {
        $page_title = "Mail Authorization";
        $user_authorize = UserAuthorization::where("token",$token)->first();
        $resend_time = 0;
        if(Carbon::now() <= $user_authorize->created_at->addMinutes(GlobalConst::USER_PASS_RESEND_TIME_MINUTE)) {
            $resend_time = Carbon::now()->diffInSeconds($user_authorize->created_at->addMinutes(GlobalConst::USER_PASS_RESEND_TIME_MINUTE));
        }
        $email = $user_authorize->user->email;
        return view('user.auth.authorize.verify-mail',compact("page_title","token","resend_time","email"));
    }

    /**
     * Verify authorization code.
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function mailVerify(Request $request,$token)
    {
        $request->merge(['token' => $token]);
        $request->validate([
            'token'     => "required|string|exists:user_authorizations,token",
            'code.*'      => "required|integer",
        ]);

        $code = implode("",$request->code);

        $otp_exp_sec = BasicSettingsProvider::get()->otp_exp_seconds ?? GlobalConst::DEFAULT_TOKEN_EXP_SEC;
        $auth_column = UserAuthorization::where("token",$request->token)->where("code",$code)->first();

        if(!$auth_column) return back()->with(['error' => ['invalid Token!']]);

        if($auth_column->created_at->addSeconds($otp_exp_sec) < now()) {
            $this->authLogout($request);
            return redirect()->route('index')->with(['error' => ['Session expired. Please try again']]);
        }

        try{
            $auth_column->user->update([
                'email_verified'    => true,
            ]);
            $auth_column->delete();
        }catch(Exception $e) {
            $this->authLogout($request);
            return redirect()->route('index')->with(['error' => ['Something went wrong! Please try again']]);
        }

        return redirect()->intended(route("user.dashboard"))->with(['success' => ['Account successfully verified']]);
    }
    /**
    * Method for resend mail using token
    */
    public function mailResend($token) {
        $user_authorize = UserAuthorization::where("token",$token)->first();
        if(!$user_authorize) return back()->with(['error' => ['Request token is invalid']]);
        if(Carbon::now() <= $user_authorize->created_at->addMinutes(GlobalConst::USER_PASS_RESEND_TIME_MINUTE)) {
            throw ValidationException::withMessages([
                'code'      => 'You can resend verification code after '.Carbon::now()->diffInSeconds($user_authorize->created_at->addMinutes(GlobalConst::USER_PASS_RESEND_TIME_MINUTE)). ' seconds',
            ]);
        }
        $resend_code = generate_random_code();
        try{
            $user_authorize->update([
                'code'          => $resend_code,
                'created_at'    => now(),
            ]);
            $data = $user_authorize->toArray();
            try{
                $user_authorize->user->notify(new SendAuthorizationCode((object) $data));
            }catch(Exception $e){}
        }catch(Exception $e) {
            throw ValidationException::withMessages([
                'code'      => "Something went wrong! Please try again.",
            ]);
        }
        
        return redirect()->route('user.authorize.mail',$token)->with(['success' => ['Mail Resend Success!']]);
    }
    public function authLogout(Request $request) {
        auth()->guard("web")->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
    }

    public function showGoogle2FAForm() {
        $page_title =  "Authorize Google Two Factor";
        return view('user.auth.authorize.verify-google-2fa',compact('page_title'));
    }

    public function google2FASubmit(Request $request) {

        $request->validate([
            'code*'      => "required|integer",
        ]);

        $code = implode($request->code);

        $user = auth()->user();

        if(!$user->two_factor_secret) {
            return back()->with(['warning' => ['Your secret key not stored properly. Please contact with system administrator']]);
        }

        if(google_2fa_verify($user->two_factor_secret,$code)) {

            $user->update([
                'two_factor_verified'   => true,
            ]);

            return redirect()->intended(route('user.dashboard'));
        }

        return back()->with(['warning' => ['Failed to login. Please try again']]);
    }
}
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"
}