/home/kueuepay/public_html/app/Http/Controllers/Api/V1/User/SaveCardController.php
<?php

namespace App\Http\Controllers\Api\V1\User;

use Exception;
use Carbon\Carbon;
use App\Models\Card;
use Illuminate\Support\Str;
use App\Constants\CardConst;
use Illuminate\Http\Request;
use App\Http\Helpers\Response;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class SaveCardController extends Controller
{
    /**
     * Method for get all the card method data
     * @return response
     */
    public function index(){
        $cards                      = Card::auth()->orderBy('id','desc')->get()->map(function($data){
            return [
                'slug'              => $data->slug,
                'name'              => decrypt($data->name),
                'type'              => $data->type,
                'card_number'       => decrypt($data->card_number),
                'card_cvc'          => decrypt($data->card_cvc),
                'expiry_date'       => decrypt($data->expiry_date),
                'default'           => $data->default,
            ];
        });
        return Response::success(['Cards data fetch successfully.'],[
            'cards'   => $cards
        ],200);

    }
    
    /**
     * Method for store the card method information
     * @return response
     * @param Illuminate\Http\Request $request
     */
    public function store(Request $request){
        $validator = Validator::make($request->all(), [
            'name'        => 'required',
            'card_number' => 'required|min:15|max:19',
            'card_cvc'    => 'required|min:3|max:4',
            'expiry_date' => 'required|min:5|max:5',
            'default'     => 'nullable'
        ]);

        if ($validator->fails()) {
            return Response::error($validator->errors()->all(),[]);
        }

        $validated = $validator->validate();

        // Remove spaces in card number and hash it for uniqueness check
        $card_number_cleaned = str_replace(' ', '', $validated['card_number']);
        
        $card_number_hash = hash('sha256', $card_number_cleaned);

        // Check if the card number hash already exists for this user
        if (Card::where('user_id', auth()->user()->id)
                ->where('card_number_hash', $card_number_hash)
                ->exists()) {
                    return Response::error(['This card number has already been added by you!'],[],400);
        }

        // Continue with validation for expiry date
        $exp_date = explode("/", $request->expiry_date);
        $month_data = str_replace(' ', '', $exp_date[0]);
        $year_data = str_replace(' ', '', $exp_date[1]);

        if ($month_data > 12) {
            return Response::error(['Invalid Month!'],[],400);
        }

        $current_month = Carbon::now()->format('m');
        $current_year = Carbon::now()->format('y');
        if ($current_year > $year_data) {
            return Response::error(['Invalid Year!'],[],400);
        }
        if ($current_month > $month_data && $current_year == $year_data) {
            return Response::error(['Month expired'],[],400);
        }

        // Encrypt sensitive data
        $validated['user_id']   = auth()->user()->id;
        $expiry_date = $month_data . '/' . $year_data;
        $validated['expiry_date'] = encrypt($expiry_date);
        $validated['type'] = CardConst::LIVE;
        $validated['slug'] = Str::uuid();
        $validated['name'] = encrypt($validated['name']);
        $validated['card_number'] = encrypt($card_number_cleaned);
        $validated['card_cvc'] = encrypt($validated['card_cvc']);
        $validated['card_number_hash'] = $card_number_hash;

        if(isset($validated['default']) != null){
            $cards      = Card::auth()->get();
            if($cards->count() != 0){
                foreach($cards ?? [] as $card){
                    try{
                        $card->update([
                            'default'    => false,
                        ]);
                    }catch(Exception $e){
                        return Response::error(['Something went wrong! Please try again.'],[],400);
                    }
                }
            }
        }

        try {
            $card = Card::create($validated);
        } catch (Exception $e) {
            return Response::error(['Something went wrong! Please try again.']);
        }

        return Response::success(['Card method created successfully.'],[],200); 
        
    }
    /**
     * Method for update the default card value
     * @param Illuminate\Http\Request $request
     */
    public function makeDefault(Request $request){
        $validator  = Validator::make($request->all(),[
            'slug'  => 'required'
        ]);
        if($validator->fails()) return Response::error($validator->errors()->all(),[]);
        $validated  = $validator->validate();

        $cards      = Card::auth()->where('slug','!=', $validated['slug'])->get();
        if($cards->count() != 0){
            foreach($cards ?? [] as $card){
                try{
                    $card->update([
                        'default'    => false,
                    ]);
                }catch(Exception $e){
                    return Response::error(['Something went wrong! Please try again.'],[],400);
                }
            }
        }
        $card       = Card::auth()->where('slug',$validated['slug'])->first();
        if(!$card) return Response::error(['Card not found!'],[],400);
        try{
            $card->update([
                'default'   => true
            ]);
        }catch(Exception $e){
            return Response::error(['Something went wrong! Please try again.'],[],400);
        }
        return Response::success(['Card status updated.'],[],200);
    }
    /**
     * Method for delete the card method
     * @return response
     * @param Illuminate\Http\Request $request
     */
    public function delete(Request $request){
        $card    = Card::where('slug',$request->slug)->first();
        if(!$card) return Response::error(['Card method not found!']);
        try{
            $card->delete();
        }catch(Exception $e){
            return Response::error(['Something went wrong! Please try again.']);
        }
        return Response::success(['Card deleted successfully.'],[],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"
}