golf_backend/app/Controllers/PaymentController.php
2023-06-02 17:28:51 +05:30

210 lines
8.0 KiB
PHP

<?php
namespace App\Controllers;
use Square\SquareClient;
use Square\Models\Money;
use Square\Models\CreatePaymentRequest;
use Square\Exceptions\ApiException;
use Ramsey\Uuid\Uuid;
use App\Models\transaction_model;
use App\Models\Member_model;
use App\Models\Dashboard_model;
use App\Models\Common_model;
use App\Models\Member_credits_model;
use App\Models\Packages_and_pricing_model;
use App\Models\Cart_model;
use App\Models\Credits_usage_tracking_model;
use App\Models\Rule_model;
class PaymentController extends BaseController
{
public function __construct()
{
$this->session = session();
$this->MemberModel = new Member_model();
$this->dModel = new Dashboard_model();
$this->cModel = new Common_model();
$this->creditsModel = new Member_credits_model();
$this->PackagesModel = new Packages_and_pricing_model();
$this->cartModel = new Cart_model();
$this->CreditsUsageTrackingModel = new Credits_usage_tracking_model();
$this->TransactionModel = new transaction_model();
$this->RuleModel = new Rule_model();
}
public function index()
{
$CartData = $this->cartModel->where('member_id',session()->get('logged_user'))->findAll();
$count = count($CartData);
if($count)
{
$credit_pack_expiry_duration = $this->RuleModel->select('value')->where('rule_key', 1 )->get()->getRow()->value;
$gst = $this->RuleModel->select('value')->where('rule_key', 3 )->get()->getRow()->value;
$pst = $this->RuleModel->select('value')->where('rule_key', 4 )->get()->getRow()->value;
$today = date("Y-m-d");
$days = "+".$credit_pack_expiry_duration." days";
$amount = 0;
$orderId = 'EGF'.rand(10,100).rand(10,100).rand(10,100);
$packageArray = [];
for($i=0;$i<$count;$i++)
{
$packageData = $this->PackagesModel->where('id',$CartData[$i]['pack_id'])->find();
$packageData[0]['count'] = $CartData[$i]['count'];
array_push($packageArray , $packageData[0]);
$cost = $packageData[0]['cost'] * $CartData[$i]['count'];
// $this->RuleModel->where('rule_key', 1 )->find()->value;
$credits_data['member_id'] = session()->get('logged_user');
$credits_data['package_name'] = $packageData[0]['package_name'];
$credits_data['package_type'] = $packageData[0]['package_type'];
$credits_data['credit_points'] = $packageData[0]['credit'];
$credits_data['running_balance'] = $packageData[0]['credit'];
$credits_data['expired_points'] = 0;
$credits_data['expiring_date'] = date('Y-m-d', strtotime($days, strtotime($today)));
$credits_data['cost'] = $packageData[0]['cost'];
$credits_data['is_active'] = 0;
$credits_data['order_id'] = $orderId;
$credits_data['cost_with_tax'] = round( ( $packageData[0]['cost'] + (($packageData[0]['cost'] * ($gst + $pst) ) / 100) ) , 2 );
$single_pack_no_of_count = $CartData[$i]['count'];
for($j=0;$j<$single_pack_no_of_count;$j++)
{
$insert_data = $this->creditsModel->save($credits_data);
}
$amount = $amount + $cost;
}
$data['amount'] = $amount;
$data['order_id'] = $orderId;
$data['gst'] = $gst;
$data['pst'] = $pst;
$data['packageArray'] = $packageArray;
$data['userdata']=$this->dModel->getLoggedInUserData(session()->get('logged_user'));
// echo '<pre>';
// print_r($data);
// echo '</pre>';
// die();
echo view('payment_form',$data);
} else { echo 'cart empty .. !'; }
}
public function payment_form()
{
return view('payment_form');
}
public function processPayment()
{
try {
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
error_log('Received a non-POST request');
echo 'Request not allowed';
http_response_code(405);
return;
}
include 'App\Libraries\LocationInfo.php';
$json = file_get_contents('php://input');
$data = json_decode($json);
$gst = $this->RuleModel->select('value')->where('rule_key', 3 )->get()->getRow()->value;
$pst = $this->RuleModel->select('value')->where('rule_key', 4 )->get()->getRow()->value;
$token = $data->token;
$idempotencyKey = $data->idempotencyKey;
$amount = $data->amount;
$order_id = $data->order_id;
$Final_amount = round( ( $amount + (($amount * ($gst + $pst) ) / 100) ) , 2 );
$square_client = new SquareClient([
'accessToken' => getenv('SQUARE_ACCESS_TOKEN'),
'environment' => getenv('ENVIRONMENT'),
'userAgentDetail' => 'golf_evo', // Remove or replace this detail when building your own app
]);
$payments_api = $square_client->getPaymentsApi();
// To learn more about splitting payments with additional recipients,
// see the Payments API documentation on our [developer site]
// (https://developer.squareup.com/docs/payments-api/overview).
$money = new Money();
// Monetary amounts are specified in the smallest unit of the applicable currency.
// This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
$money->setAmount($Final_amount);
// Set currency to the currency for the location
$money->setCurrency($location_info->getCurrency());
//print_r($money); die();
try {
// Every payment you process with the SDK must have a unique idempotency key.
// If you're unsure whether a particular payment succeeded, you can reattempt
// it with the same idempotency key without worrying about double charging
// the buyer.
$create_payment_request = new CreatePaymentRequest($token, $idempotencyKey, $money);
$create_payment_request->setLocationId($location_info->getId());
$response = $payments_api->createPayment($create_payment_request);
if ($response->isSuccess()) {
echo json_encode($response->getResult());
$TrancactionId = $response->getResult()->payment->id;
$TrancactionData['member_id'] = session()->get('logged_user');
$TrancactionData['transaction'] = json_encode($response->getResult());
$this->TransactionModel->save($TrancactionData);
$this->creditsModel->where('order_id', $order_id )->where('member_id', session()->get('logged_user'))
->set(array( 'is_active' => 1 , 'transaction_id' => $TrancactionId ))->update();
} else {
echo json_encode(array('errors' => $response->getErrors()));
}
} catch (ApiException $e) {
echo json_encode(array('errors' => $e));
}
} catch (\Exception $e) {
// Handle exceptions
// Example: Logging the exception
log_message('error', 'Exception: ' . $e->getMessage());
// Example: Displaying a custom error message
echo 'An exception occurred: ' . $e->getMessage();
} catch (\Error $e) {
// Handle errors
// Example: Logging the error
log_message('error', 'Error: ' . $e->getMessage());
// Example: Displaying a custom error message
echo 'An error occurred: ' . $e->getMessage();
}
}
}