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

313 lines
11 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-12-01 11:19:06 +00:00
use App\Models\invoiceSettings;
2021-06-05 09:26:32 +00:00
use App\Models\Payment;
use App\Models\PaypalProduct;
use App\Models\User;
2021-11-27 01:47:36 +00:00
use App\Notifications\InvoiceNotification;
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;
2021-11-30 13:52:36 +00:00
use Illuminate\Support\Facades\Storage;
2021-11-30 17:40:56 +00:00
use LaravelDaily\Invoices\Classes\Buyer;
use LaravelDaily\Invoices\Classes\InvoiceItem;
2021-11-26 19:42:38 +00:00
use LaravelDaily\Invoices\Classes\Party;
2021-11-30 17:40:56 +00:00
use LaravelDaily\Invoices\Invoice;
2021-06-05 09:26:32 +00:00
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\ProductionEnvironment;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use PayPalHttp\HttpException;
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
* @param PaypalProduct $paypalProduct
* @return Application|Factory|View
*/
public function checkOut(Request $request, PaypalProduct $paypalProduct)
{
return view('store.checkout')->with([
2021-11-30 17:40:56 +00:00
'product' => $paypalProduct,
'taxvalue' => $paypalProduct->getTaxValue(),
'taxpercent' => $paypalProduct->getTaxPercent(),
'total' => $paypalProduct->getTotalPrice()
2021-06-05 09:26:32 +00:00
]);
}
/**
* @param Request $request
* @param PaypalProduct $paypalProduct
* @return RedirectResponse
*/
public function pay(Request $request, PaypalProduct $paypalProduct)
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-06-17 18:35:13 +00:00
"description" => $paypalProduct->description,
2021-11-30 17:40:56 +00:00
"amount" => [
"value" => $paypalProduct->getTotalPrice(),
2021-11-05 06:43:57 +00:00
'currency_code' => strtoupper($paypalProduct->currency_code),
2021-11-30 17:40:56 +00:00
'breakdown' => [
2021-11-05 06:43:57 +00:00
'item_total' =>
2021-11-30 17:40:56 +00:00
[
2021-11-05 06:43:57 +00:00
'currency_code' => strtoupper($paypalProduct->currency_code),
'value' => $paypalProduct->price,
],
'tax_total' =>
[
'currency_code' => strtoupper($paypalProduct->currency_code),
2021-11-05 16:38:05 +00:00
'value' => $paypalProduct->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'),
"return_url" => route('payment.success', ['product' => $paypalProduct->id]),
2021-11-30 17:40:56 +00:00
'brand_name' => config('app.name', 'Laravel'),
'shipping_preference' => 'NO_SHIPPING'
2021-06-05 09:26:32 +00:00
]
2021-11-05 06:59:25 +00:00
2021-11-26 19:42:38 +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'
? new SandboxEnvironment($this->getClientId(), $this->getClientSecret())
: new ProductionEnvironment($this->getClientId(), $this->getClientSecret());
return new PayPalHttpClient($environment);
}
/**
* @return string
*/
protected function getClientId()
{
return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_CLIENT_ID');
}
/**
* @return string
*/
protected function getClientSecret()
{
return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_SECRET') : env('PAYPAL_SECRET');
}
/**
* @param Request $laravelRequest
*/
public function success(Request $laravelRequest)
{
/** @var PaypalProduct $paypalProduct */
2021-06-05 09:26:32 +00:00
$paypalProduct = PaypalProduct::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
$user->increment('credits', $paypalProduct->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-11-26 19:42:38 +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,
'payer_id' => $laravelRequest->input('PayerID'),
'type' => 'Credits',
'status' => $response->result->status,
'amount' => $paypalProduct->quantity,
'price' => $paypalProduct->price,
2021-11-05 16:38:05 +00:00
'tax_value' => $paypalProduct->getTaxValue(),
'tax_percent' => $paypalProduct->getTaxPercent(),
'total_price' => $paypalProduct->getTotalPrice(),
'currency_code' => $paypalProduct->currency_code,
2021-06-05 09:26:32 +00:00
'payer' => json_encode($response->result->payer),
]);
event(new UserUpdateCreditsEvent($user));
2021-11-26 19:42:38 +00:00
//create invoice
2021-12-01 11:19:06 +00:00
$lastInvoiceID = \App\Models\invoice::where("invoice_name", "like", "%" . now()->format('mY') . "%")->count("id");
2021-11-30 14:50:43 +00:00
$newInvoiceID = $lastInvoiceID + 1;
2021-12-01 11:19:06 +00:00
$invoiceSettings = invoiceSettings::all()->first();
2021-11-30 14:50:43 +00:00
2021-11-26 19:42:38 +00:00
$seller = new Party([
2021-12-01 11:19:06 +00:00
'name' => $invoiceSettings->company_name,
'phone' => $invoiceSettings->company_phone,
'address' => $invoiceSettings->company_adress,
'vat' => $invoiceSettings->company_vat,
2021-11-26 19:42:38 +00:00
'custom_fields' => [
2021-12-01 11:19:06 +00:00
'E-Mail' => $invoiceSettings->company_mail,
"Web" => $invoiceSettings->company_web
2021-11-26 19:42:38 +00:00
],
]);
$customer = new Buyer([
2021-11-30 17:40:56 +00:00
'name' => $user->name,
2021-11-26 19:42:38 +00:00
'custom_fields' => [
2021-11-30 14:50:43 +00:00
'E-Mail' => $user->email,
'Client ID' => $user->id,
2021-11-26 19:42:38 +00:00
],
]);
$item = (new InvoiceItem())->title($paypalProduct->description)->pricePerUnit($paypalProduct->price);
$invoice = Invoice::make()
->buyer($customer)
->seller($seller)
->discountByPercent(0)
->taxRate(floatval($paypalProduct->getTaxPercent()))
->shipping(0)
->addItem($item)
->status(__('invoices::invoice.paid'))
2021-11-30 14:50:43 +00:00
->series(now()->format('mY'))
2021-11-27 01:47:36 +00:00
->delimiter("-")
->sequence($newInvoiceID)
2021-11-30 17:40:56 +00:00
->serialNumberFormat(env("INVOICE_PREFIX", "INV") . '{DELIMITER}{SERIES}{SEQUENCE}')
2021-12-01 11:19:06 +00:00
->logo(storage_path('app/public/logo.png'));
2021-11-30 15:30:48 +00:00
2021-11-30 13:52:36 +00:00
//Save the invoice in "storage\app\invoice\USER_ID\YEAR"
2021-11-30 17:40:56 +00:00
$invoice->filename = $invoice->getSerialNumber() . '.pdf';
2021-11-30 13:52:36 +00:00
$invoice->render();
2021-11-30 17:40:56 +00:00
Storage::disk("local")->put("invoice/" . $user->id . "/" . now()->format('Y') . "/" . $invoice->filename, $invoice->output);
2021-11-26 19:42:38 +00:00
2021-11-27 01:47:36 +00:00
\App\Models\invoice::create([
'invoice_user' => $user->id,
2021-11-30 17:18:15 +00:00
'invoice_name' => $invoice->getSerialNumber(),
2021-11-27 01:47:36 +00:00
'payment_id' => $payment->payment_id,
]);
2021-11-30 17:18:15 +00:00
//Send Invoice per Mail
2021-12-01 11:32:46 +00:00
$user->notify(new InvoiceNotification($invoice, $user, $payment));
2021-11-30 17:18:15 +00:00
2021-06-05 09:26:32 +00:00
//redirect back to home
2021-11-30 17:18:15 +00:00
return redirect()->route('home')->with('success', 'Your credit balance has been increased!');
2021-06-05 09:26:32 +00:00
}
2021-11-27 01:47:36 +00:00
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-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
}
/**
* @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('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
}