ctrlpanel/app/Http/Controllers/Admin/PaymentController.php

403 lines
13 KiB
PHP
Raw Normal View History

2021-06-05 09:26:32 +00:00
<?php
namespace App\Http\Controllers\Admin;
use App\Events\UserUpdateCreditsEvent;
2021-06-05 09:26:32 +00:00
use App\Http\Controllers\Controller;
use App\Models\Configuration;
2021-06-05 09:26:32 +00:00
use App\Models\Payment;
2021-12-12 23:58:47 +00:00
use App\Models\CreditProduct;
use App\Models\Product;
use App\Models\User;
use App\Notifications\ConfirmPaymentNotification;
use Exception;
2021-06-05 09:26:32 +00:00
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
2021-06-05 09:26:32 +00:00
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\ProductionEnvironment;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use PayPalHttp\HttpException;
2021-12-13 01:48:02 +00:00
use Stripe\Stripe;
2021-06-05 09:26:32 +00:00
class PaymentController extends Controller
{
2021-11-04 20:42:17 +00:00
/**
* @return Application|Factory|View
*/
public function index()
{
2021-06-05 09:26:32 +00:00
return view('admin.payments.index')->with([
'payments' => Payment::paginate(15)
]);
}
/**
* @param Request $request
2021-12-12 23:58:47 +00:00
* @param CreditProduct $creditProduct
2021-06-05 09:26:32 +00:00
* @return Application|Factory|View
*/
2021-12-12 23:58:47 +00:00
public function checkOut(Request $request, CreditProduct $creditProduct)
2021-06-05 09:26:32 +00:00
{
return view('store.checkout')->with([
2021-12-12 23:58:47 +00:00
'product' => $creditProduct,
'taxvalue' => $creditProduct->getTaxValue(),
'taxpercent' => $creditProduct->getTaxPercent(),
'total' => $creditProduct->getTotalPrice()
2021-06-05 09:26:32 +00:00
]);
}
/**
* @param Request $request
2021-12-12 23:58:47 +00:00
* @param CreditProduct $creditProduct
2021-06-05 09:26:32 +00:00
* @return RedirectResponse
*/
2021-12-13 01:48:02 +00:00
public function PaypalPay(Request $request, CreditProduct $creditProduct)
2021-06-05 09:26:32 +00:00
{
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = [
"intent" => "CAPTURE",
"purchase_units" => [
2021-06-05 09:26:32 +00:00
[
"reference_id" => uniqid(),
2021-12-12 23:58:47 +00:00
"description" => $creditProduct->description,
2021-06-05 09:26:32 +00:00
"amount" => [
2021-12-12 23:58:47 +00:00
"value" => $creditProduct->getTotalPrice(),
'currency_code' => strtoupper($creditProduct->currency_code),
2021-11-05 06:43:57 +00:00
'breakdown' =>[
'item_total' =>
[
2021-12-12 23:58:47 +00:00
'currency_code' => strtoupper($creditProduct->currency_code),
'value' => $creditProduct->price,
2021-11-05 06:43:57 +00:00
],
'tax_total' =>
[
2021-12-12 23:58:47 +00:00
'currency_code' => strtoupper($creditProduct->currency_code),
'value' => $creditProduct->getTaxValue(),
2021-11-05 06:43:57 +00:00
]
]
2021-06-05 09:26:32 +00:00
]
2021-11-05 06:59:25 +00:00
]
],
2021-06-05 09:26:32 +00:00
"application_context" => [
"cancel_url" => route('payment.Cancel'),
2021-12-12 23:58:47 +00:00
"return_url" => route('payment.PaypalSuccess', ['product' => $creditProduct->id]),
2021-06-16 14:35:07 +00:00
'brand_name' => config('app.name', 'Laravel'),
2021-06-23 10:32:20 +00:00
'shipping_preference' => 'NO_SHIPPING'
2021-06-05 09:26:32 +00:00
]
2021-11-05 06:59:25 +00:00
2021-12-12 23:58:47 +00:00
2021-06-05 09:26:32 +00:00
];
try {
// Call API with your client and get a response for your call
$response = $this->getPayPalClient()->execute($request);
return redirect()->away($response->result->links[1]->href);
// If call returns body in response, you can get the deserialized version from the result attribute of the response
} catch (HttpException $ex) {
echo $ex->statusCode;
dd(json_decode($ex->getMessage()));
}
}
/**
* @return PayPalHttpClient
*/
protected function getPayPalClient()
{
$environment = env('APP_ENV') == 'local'
2021-12-12 23:58:47 +00:00
? new SandboxEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret())
: new ProductionEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret());
2021-06-05 09:26:32 +00:00
return new PayPalHttpClient($environment);
}
/**
* @return string
*/
2021-12-12 23:58:47 +00:00
protected function getPaypalClientId()
2021-06-05 09:26:32 +00:00
{
return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_CLIENT_ID');
}
/**
* @return string
*/
2021-12-12 23:58:47 +00:00
protected function getPaypalClientSecret()
2021-06-05 09:26:32 +00:00
{
return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_SECRET') : env('PAYPAL_SECRET');
}
/**
* @param Request $laravelRequest
*/
2021-12-12 23:58:47 +00:00
public function PaypalSuccess(Request $laravelRequest)
2021-06-05 09:26:32 +00:00
{
2021-12-12 23:58:47 +00:00
/** @var CreditProduct $creditProduct */
$creditProduct = CreditProduct::findOrFail($laravelRequest->input('product'));
/** @var User $user */
$user = Auth::user();
2021-06-05 09:26:32 +00:00
$request = new OrdersCaptureRequest($laravelRequest->input('token'));
$request->prefer('return=representation');
try {
// Call API with your client and get a response for your call
$response = $this->getPayPalClient()->execute($request);
if ($response->statusCode == 201 || $response->statusCode == 200) {
//update credits
2021-12-12 23:58:47 +00:00
$user->increment('credits', $creditProduct->quantity);
2021-06-05 09:26:32 +00:00
//update server limit
if (Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
if ($user->server_limit < Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
$user->update(['server_limit' => Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
}
2021-06-05 09:26:32 +00:00
}
2021-12-12 23:58:47 +00:00
2021-06-05 09:26:32 +00:00
//update role
if ($user->role == 'member') {
$user->update(['role' => 'client']);
2021-06-05 09:26:32 +00:00
}
//store payment
$payment = Payment::create([
'user_id' => $user->id,
2021-06-05 09:26:32 +00:00
'payment_id' => $response->result->id,
2021-12-15 10:41:57 +00:00
'payment_method' => 'paypal',
2021-06-05 09:26:32 +00:00
'type' => 'Credits',
'status' => 'paid',
2021-12-12 23:58:47 +00:00
'amount' => $creditProduct->quantity,
'price' => $creditProduct->price,
'tax_value' => $creditProduct->getTaxValue(),
'tax_percent' => $creditProduct->getTaxPercent(),
'total_price' => $creditProduct->getTotalPrice(),
'currency_code' => $creditProduct->currency_code,
2021-06-05 09:26:32 +00:00
]);
//payment notification
$user->notify(new ConfirmPaymentNotification($payment));
event(new UserUpdateCreditsEvent($user));
2021-06-05 09:26:32 +00:00
//redirect back to home
2021-06-16 14:35:07 +00:00
return redirect()->route('home')->with('success', 'Your credit balance has been increased!');
2021-06-05 09:26:32 +00:00
}
// If call returns body in response, you can get the deserialized version from the result attribute of the response
if (env('APP_ENV') == 'local') {
dd($response);
} else {
abort(500);
}
} catch (HttpException $ex) {
if (env('APP_ENV') == 'local') {
echo $ex->statusCode;
dd($ex->getMessage());
} else {
abort(422);
}
}
}
/**
* @param Request $request
*/
public function Cancel(Request $request)
2021-06-05 09:26:32 +00:00
{
2021-11-05 07:45:29 +00:00
return redirect()->route('store.index')->with('success', 'Payment was Canceled');
2021-06-05 09:26:32 +00:00
}
2021-12-13 01:48:02 +00:00
/**
* @param Request $request
* @param CreditProduct $creditProduct
* @return RedirectResponse
*/
public function StripePay(Request $request, CreditProduct $creditProduct)
{
$stripeClient = $this->getStripeClient();
2021-12-15 10:41:57 +00:00
$request = $stripeClient->checkout->sessions->create([
2021-12-13 01:48:02 +00:00
'line_items' => [
[
'price_data' => [
'currency' => $creditProduct->currency_code,
2021-12-13 01:48:02 +00:00
'product_data' => [
'name' => $creditProduct->display,
'description' => $creditProduct->description,
],
'unit_amount_decimal' => round($creditProduct->price*100, 2),
],
'quantity' => 1,
],
[
'price_data' => [
'currency' => $creditProduct->currency_code,
2021-12-13 01:48:02 +00:00
'product_data' => [
'name' => 'Product Tax',
'description' => $creditProduct->getTaxPercent() . "%",
],
'unit_amount_decimal' => round($creditProduct->getTaxValue(), 2)*100,
],
'quantity' => 1,
]
],
2021-12-13 01:48:02 +00:00
'mode' => 'payment',
'payment_intent_data' => [
'capture_method' => 'manual',
],
'success_url' => route('payment.StripeSuccess', ['product' => $creditProduct->id]).'&session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => route('payment.Cancel'),
2021-12-13 01:48:02 +00:00
]);
return redirect($request->url, 303);
}
/**
* @param Request $request
*/
public function StripeSuccess(Request $request)
{
/** @var CreditProduct $creditProduct */
$creditProduct = CreditProduct::findOrFail($request->input('product'));
/** @var User $user */
$user = Auth::user();
$stripeClient = $this->getStripeClient();
try{
2021-12-15 10:41:57 +00:00
$paymentSession = $stripeClient->checkout->sessions->retrieve($request->input('session_id'));
$capturedPaymentIntent = $stripeClient->paymentIntents->capture($paymentSession->payment_intent);
if ($capturedPaymentIntent->status == "succeeded") {
//update credits
$user->increment('credits', $creditProduct->quantity);
//update server limit
if (Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
if ($user->server_limit < Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
$user->update(['server_limit' => Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
}
}
//update role
if ($user->role == 'member') {
$user->update(['role' => 'client']);
}
//store payment
$payment = Payment::create([
'user_id' => $user->id,
2021-12-15 10:41:57 +00:00
'payment_id' => $capturedPaymentIntent->id,
'payment_method' => 'stripe',
'type' => 'Credits',
'status' => 'paid',
'amount' => $creditProduct->quantity,
'price' => $creditProduct->price,
'tax_value' => $creditProduct->getTaxValue(),
'total_price' => $creditProduct->getTotalPrice(),
2021-12-15 10:41:57 +00:00
'tax_percent' => $creditProduct->getTaxPercent(),
'currency_code' => $creditProduct->currency_code,
]);
//payment notification
$user->notify(new ConfirmPaymentNotification($payment));
event(new UserUpdateCreditsEvent($user));
//redirect back to home
return redirect()->route('home')->with('success', 'Your credit balance has been increased!');
}
}catch (HttpException $ex) {
if (env('APP_ENV') == 'local') {
echo $ex->statusCode;
dd($ex->getMessage());
} else {
abort(422);
}
}
}
/**
* @return StripeClient
*/
protected function getStripeClient()
{
$environment = env('APP_ENV') == 'local'
? $this->getStripeSecret()
: $this->getStripeSecret();
return new \Stripe\StripeClient($environment);
}
/**
2021-12-13 01:48:02 +00:00
* @return string
*/
protected function getStripeClientId()
{
return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_CLIENT_ID');
}
/**
* @return string
*/
protected function getStripeSecret()
2021-12-13 01:48:02 +00:00
{
return env('STRIPE_SECRET');
}
/**
* @return JsonResponse|mixed
* @throws Exception
*/
public function dataTable()
{
$query = Payment::with('user');
return datatables($query)
->editColumn('user', function (Payment $payment) {
return $payment->user->name;
})
->editColumn('price', function (Payment $payment) {
2021-11-05 08:00:18 +00:00
return $payment->formatToCurrency($payment->price);
})
->editColumn('tax_value', function (Payment $payment) {
return $payment->formatToCurrency($payment->tax_value);
})
->editColumn('tax_percent', function (Payment $payment) {
return $payment->tax_percent . ' %';
})
2021-11-05 08:00:18 +00:00
->editColumn('total_price', function (Payment $payment) {
return $payment->formatToCurrency($payment->total_price);
})
->editColumn('created_at', function (Payment $payment) {
return $payment->created_at ? $payment->created_at->diffForHumans() : '';
})
->make();
}
2021-06-05 09:26:32 +00:00
}