Viewing File: /home/ubuntu/vedadeals-backend-base/app/Services/PaymentService.php

<?php 

namespace App\Services;

use App\Models\{ User, UserWallet, UserWithdrawal, UserWalletPayment, UserCard, OrderPayment };

use DB, Exception, Setting, stdClass;

class PaymentService {

	/**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(Request $request)
    {

    }

    /**
     * @method update_user_wallet()
     *
     * @uses add / minus amount to user wallet.
     *
     * @created Karthick
     * 
     * @updated
     *
     * @param user_id, amount, type
     *
     * @return 
     */

    public static function update_user_wallet($user_id, $amount, $type) {
        
        try {

            $user_wallet = UserWallet::firstOrCreate(['user_id' => $user_id]);

            if(in_array($type, [WALLET_PAYMENT_TYPE_ADD, WALLET_PAYMENT_TYPE_CREDIT])) {

                $user_wallet->remaining += $amount;

                $user_wallet->total = $type == WALLET_PAYMENT_TYPE_CREDIT ? $user_wallet->total + $amount : $user_wallet->total;

                $user_wallet->used = $type == WALLET_PAYMENT_TYPE_ADD ? $user_wallet->used - $amount : $user_wallet->used;

            } elseif(in_array($type, [WALLET_PAYMENT_TYPE_PAID, WALLET_PAYMENT_TYPE_WITHDRAWAL])) {

                $user_wallet->used += $amount;

                $user_wallet->remaining = $type == WALLET_PAYMENT_TYPE_PAID ? $user_wallet->remaining - $amount : $user_wallet->remaining;

                $user_wallet->onhold = $type == WALLET_PAYMENT_TYPE_WITHDRAWAL ? $user_wallet->onhold - $amount : $user_wallet->onhold;
            }

            $user_wallet->save();

            $response_array = ['result' => true, 'message' => 'User Wallet Updated Successfully', 'data' => $user_wallet];

            return response()->json($response_array, 200);

        } catch(Exception $e) {

            $response = ['result' => false, 'error' => $e->getMessage(), 'error_code' => $e->getCode()];

            return response()->json($response, 200);
        }
    }

	/**
     * @method user_wallet_payment_save()
     *
     * @uses to handle calculation, save user wallet payment and update the wallet when user make transactions.
     *
     * @created Karthick
     *
     * @updated  
     *
     */	

	public function user_wallet_payment_save($payment_data) {

		try {

			$user = User::find($payment_data->user_id);

			if(!$user) {

				throw new Exception(api_error(100), 100);
			}

			$user_wallet = UserWallet::firstOrCreate(['user_id' => $user->id]);

			DB::beginTransaction();

			$user_wallet_payment = UserWalletPayment::Create([
													'user_id' => $user->id,
													'payment_id' => "UW-P-".generate_payment_id(),
                                                    'user_billing_account_id' => $payment_data->user_billing_account_id ? : 0,
													'requested_amount' => $payment_data->amount ? : 0.00,
													'paid_amount' => $payment_data->amount ? : 0.00,
                                                    'amount' => $payment_data->amount ? : 0.00,
													'message' => tr('paid'),
													'amount_type' => $payment_data->amount_type,
													'payment_type' => $payment_data->payment_type,
													'payment_mode' => $payment_data->payment_mode,
													'payment_status' => PAID,
													'status' => APPROVED,
													'paid_date' => now(),
												]);

            $user_wallet_result = self::update_user_wallet($user_wallet_payment->user_id, $user_wallet_payment->paid_amount, $user_wallet_payment->payment_type)->getData();

			if($user_wallet_payment && $user_wallet_result->result) {

				DB::commit();

				$response_array = ['result' => true, 'message' => tr('user_wallet_payment_save_success'), 'user_wallet_payment' => $user_wallet_payment->id];

				return $response_array;
			}

			throw new Exception(tr('user_wallet_payment_save_failed')); 

		} catch(Exception $e) {

			DB::rollback();

			$response_array = ['result' => false, 'message' => $e->getMessage()];

			return $response_array;
		}
	}

	/**
     * @method user_wallet_payment_by_stripe()
     *
     * @uses to add amount to user wallet payment by stripe
     *
     * @created Karthick
     * 
     * @updated 
     *
     * @param object $user_id, $amount, $card_id
     *
     * @return success / failure status
     */

    public static function user_wallet_payment_by_stripe($user_id, $amount, $user_card_id) {

        try {
        
            $stripe_secret_key = Setting::get('stripe_secret_key');

            if(!$stripe_secret_key) {

                throw new Exception(api_error(105), 105);

            } 

            \Stripe\Stripe::setApiKey($stripe_secret_key);
           
            $currency_code = Setting::get('currency_code', 'USD');

            if($user_card_id) {

                $user_card = UserCard::firstWhere(['id' => $user_card_id, 'user_id' => $user_id]);

            } else {

                $user_card = UserCard::firstWhere(['user_id' => $user_id, 'is_default' => YES]);

            }

            $total = intval(round($amount * 100));

            $charge_array = [
                'amount' => $total,
                'currency' => $currency_code,
                'customer' => $user_card->customer_id,
                "payment_method" => $user_card->card_token,
                'off_session' => true,
                'confirm' => true,
            ];

            $stripe_payment_response = \Stripe\PaymentIntent::create($charge_array);

            $data = [
	                    'payment_id' => $stripe_payment_response->id ? : 'CARD-'.rand(),
	                    'paid_amount' => $stripe_payment_response->amount/100 ? : $total,
	                    'paid_status' => $stripe_payment_response->paid ? : true
                    ];

            $response_array = ['result' => true, 'message' => 'done', 'data' => $data];

            return $response_array;

        } catch(Exception $e) {

            $response_array = ['result' => false, 'message' => $e->getMessage(), 'error_code' => $e->getCode()];

            return $response_array;

        }

    }

    /**
     * @method get_withdrawal_status()
     *
     * @uses to validate a withdrawal request status
     *
     * @created Karthick
     *
     * @updated  
     *
     */

    public function get_withdrawal_status($status) { 

        $withdrawal_status['result'] = false;

         if(in_array($status, [PAID, CANCELLED, REJECTED])) {

            $withdrawal_status['result'] = true;

            $status_code = [ PAID => 116, CANCELLED => 117 , REJECTED => 118 ];

            $withdrawal_status['code'] = $status_code[$status];

            return $withdrawal_status;
         }

         return $withdrawal_status;
    }

    /**
     * @method add_withdrawal_request()
     *
     * @uses to handle calculation and update the wallet when user send a withdrawal request
     *
     * @created Karthick
     *
     * @updated  
     *
     */

    public function add_withdrawal_request($withdrawal_data) {

        try {

            $user = User::find($withdrawal_data->user_id);

            if(!$user) {

                throw new Exception(tr('user_not_found'));
            }

            $user_wallet = UserWallet::firstOrCreate(['user_id' => $user->id]);

            DB::beginTransaction();

            $user_withdrawal = UserWithdrawal::Create([ 
                'user_id' => $user->id, 
                'requested_amount' => $withdrawal_data->amount, 
                'user_billing_account_id' => $withdrawal_data->user_billing_account_id,
                'payment_mode' => ''
            ]);

            $result = $user_wallet->update(['remaining' => $user_wallet->remaining - $withdrawal_data->amount, 'onhold' => $user_wallet->onhold + $withdrawal_data->amount]);

            if($user_withdrawal && $result) {

                DB::commit();

                $response_array = ['result' => true, 'message' => api_success(128), 'data' => $user_withdrawal];

                return $response_array;

            }

            throw new Exception(api_error(115)); 

        } catch(Exception $e) {

            DB::rollback();

            $response_array = ['result' => false, 'message' => $e->getMessage()];

            return $response_array;
        }
    }

    /**
     * @method cancel_withdrawal_request()
     *
     * @uses to handle calculation and update the wallet when user cancel a withdrawal request
     *
     * @created Karthick
     *
     * @updated  
     *
     */

    public function cancel_withdrawal_request($user_withdrawal_id, $cancel_reason = '') {

        try {

            $user_withdrawal = UserWithdrawal::find($user_withdrawal_id);

            $user_wallet = UserWallet::firstOrCreate(['user_id' => $user_withdrawal->user_id]);

            $user = User::find($user_withdrawal->user_id);

            if(!$user) {

                throw new Exception(tr('user_not_found'));
            }

            DB::beginTransaction();

            $result = $user_withdrawal->update(['is_cancelled' => YES, 'status' => CANCELLED, 'cancel_reason' => $cancel_reason]);

            $user_wallet = $user_wallet->update([
                'remaining' => $user_wallet->remaining + $user_withdrawal->requested_amount, 
                'onhold' => $user_wallet->onhold - $user_withdrawal->requested_amount
            ]);

            if($result && $user_wallet) {

                DB::commit();

                if (Setting::get('is_email_notification') == YES) {

                    EmailService::send_withdrawal_request_cancelled_email($user_withdrawal);

                }

                $response_array = ['result' => true, 'message' => api_success(129)];

                return $response_array;
            }

            throw new Exception(api_error(119)); 

        } catch(Exception $e) {

            DB::rollback();

            $response_array = ['result' => false, 'message' => $e->getMessage()];

            return $response_array;
        }
    }

    /**
     * @method reject_withdrawal_request()
     *
     * @uses to handle calculation and update the wallet when admin reject a withdrawal request
     *
     * @created Karthick
     *
     * @updated  
     *
     */

    public function reject_withdrawal_request($user_withdrawal_id, $cancel_reason = '') {

        try {

            $user_withdrawal = UserWithdrawal::find($user_withdrawal_id);

            $wallet = UserWallet::firstOrCreate(['user_id' => $user_withdrawal->user_id]);

            $user = User::find($user_withdrawal->user_id);

            if(!$user) {

                throw new Exception(tr('user_not_found'));
            }

            DB::beginTransaction();

            $result = $user_withdrawal->update([ 'status' => REJECTED, 'cancel_reason' => $cancel_reason]);

            $wallet = $wallet->update(['remaining' => $wallet->remaining + $user_withdrawal->requested_amount, 'onhold' => $wallet->onhold - $user_withdrawal->requested_amount]);

            if($result && $wallet) {

                DB::commit();

                if (Setting::get('is_email_notification') == YES) {

                    EmailService::send_withdrawal_request_rejected_email($user_withdrawal);

                }

                $response_array = ['result' => true, 'message' => api_success(118)];

                return $response_array;
            }

            throw new Exception(api_error(1021)); 

        } catch(Exception $e) {

            DB::rollback();

            $response_array = ['result' => false, 'message' => $e->getMessage()];

            return $response_array;
        }
    }

    /**
     * @method pay_withdrawal_request()
     *
     * @uses to handle calculation and update the wallet when admin pay for user
     *
     * @created Karthick
     *
     * @updated  
     *
     */ 

    public function pay_withdrawal_request($withdrawal_id, $amount) {

        try {

            $user_withdrawal = UserWithdrawal::find($withdrawal_id);

            $wallet = UserWallet::firstOrCreate(['user_id' => $user_withdrawal->user_id]);

            $user = User::find($user_withdrawal->user_id);

            if(!$user) {

                throw new Exception(tr('user_not_found'));
            }

            DB::beginTransaction();

            $payment_data = new stdClass;

            $payment_data->user_id = $user->id; $payment_data->amount = $amount;

            $payment_data->amount_type = AMOUNT_TYPE_MINUS; $payment_data->payment_type = WALLET_PAYMENT_TYPE_WITHDRAWAL;

            $payment_data->payment_mode = PAYMENT_MODE_WALLET;

            $payment_data->user_billing_account_id = $user_withdrawal->user_billing_account_id;

            $user_wallet_payment = self::user_wallet_payment_save($payment_data);

            $result = $user_withdrawal->update([
                                    'user_wallet_payment_id' => $user_wallet_payment['user_wallet_payment'],
                                    'payment_id' => "UW-".$user_withdrawal->id."-".generate_payment_id(),
                                    'paid_amount' => $amount,
                                    'payment_mode' => PAYMENT_MODE_WALLET,
                                    'status' => PAID
                                ]);

            if($user_wallet_payment['result'] && $result && $wallet) {

                DB::commit();

                EmailService::send_withdrawal_request_paid_email($user->id, $amount);

                $response_array = ['result' => true, 'message' => tr('withdrawal_request_paid_success')];

                return $response_array;
            }

            throw new Exception(tr('withdrawal_request_paid_failure')); 

        } catch(Exception $e) {

            DB::rollback();

            $response_array = ['result' => false, 'message' => $e->getMessage()];

            return $response_array;
        }
    }

    /**
     * @method user_card_payment_save()
     *
     * @uses to complete order payment by user card
     *
     * @created Karthick
     * 
     * @updated 
     *
     * @param object $user_id, $amount
     *
     * @return success / failure status
     */

    public static function user_card_payment_save($payment_data) {

        try {
        
            $stripe_secret_key = Setting::get('stripe_secret_key');

            if(!$stripe_secret_key) {

                throw new Exception(api_error(105), 105);

            } 

            \Stripe\Stripe::setApiKey($stripe_secret_key);
           
            $currency_code = Setting::get('currency_code', 'USD');

            $user_card = UserCard::firstWhere(['user_id' => $payment_data->user_id, 'id' => $payment_data->user_card_id]);

            $total = intval(round($payment_data->amount * 100));

            $charge_array = [
                'amount' => $total,
                'currency' => $currency_code,
                'customer' => $user_card->customer_id,
                "payment_method" => $user_card->card_token,
                'off_session' => true,
                'confirm' => true,
            ];

            $stripe_payment_response = \Stripe\PaymentIntent::create($charge_array);

            $data = [
                        'payment_id' => $stripe_payment_response->id ? : 'CARD-'.rand(),
                        'paid_amount' => $stripe_payment_response->amount/100 ? : $total,
                        'paid_status' => $stripe_payment_response->paid ? : true
                    ];

            $response_array = ['result' => true, 'message' => 'done', 'data' => $data];

            return $response_array;

        } catch(Exception $e) {

            $response_array = ['result' => false, 'message' => $e->getMessage(), 'error_code' => $e->getCode()];

            return $response_array;

        }

    }

}
Back to Directory File Manager