PaymentController.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Events\UserUpdateCreditsEvent;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\InvoiceSettings;
  6. use App\Models\Payment;
  7. use App\Models\ShopProduct;
  8. use App\Models\Settings;
  9. use App\Models\User;
  10. use App\Notifications\InvoiceNotification;
  11. use App\Notifications\ConfirmPaymentNotification;
  12. use Exception;
  13. use Illuminate\Contracts\Foundation\Application;
  14. use Illuminate\Contracts\View\Factory;
  15. use Illuminate\Contracts\View\View;
  16. use Illuminate\Http\JsonResponse;
  17. use Illuminate\Http\RedirectResponse;
  18. use Illuminate\Http\Request;
  19. use Illuminate\Support\Facades\Auth;
  20. use Illuminate\Support\Facades\Storage;
  21. use LaravelDaily\Invoices\Classes\Buyer;
  22. use LaravelDaily\Invoices\Classes\InvoiceItem;
  23. use LaravelDaily\Invoices\Classes\Party;
  24. use LaravelDaily\Invoices\Invoice;
  25. use PayPalCheckoutSdk\Core\PayPalHttpClient;
  26. use PayPalCheckoutSdk\Core\ProductionEnvironment;
  27. use PayPalCheckoutSdk\Core\SandboxEnvironment;
  28. use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
  29. use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
  30. use PayPalHttp\HttpException;
  31. use Stripe\Stripe;
  32. use Symfony\Component\Intl\Currencies;
  33. class PaymentController extends Controller
  34. {
  35. /**
  36. * @return Application|Factory|View
  37. */
  38. public function index()
  39. {
  40. return view('admin.payments.index')->with([
  41. 'payments' => Payment::paginate(15)
  42. ]);
  43. }
  44. /**
  45. * @param Request $request
  46. * @param ShopProduct $shopProduct
  47. * @return Application|Factory|View
  48. */
  49. public function checkOut(Request $request, ShopProduct $shopProduct)
  50. {
  51. return view('store.checkout')->with([
  52. 'product' => $shopProduct,
  53. 'taxvalue' => $shopProduct->getTaxValue(),
  54. 'taxpercent' => $shopProduct->getTaxPercent(),
  55. 'total' => $shopProduct->getTotalPrice()
  56. ]);
  57. }
  58. /**
  59. * @param Request $request
  60. * @param ShopProduct $shopProduct
  61. * @return RedirectResponse
  62. */
  63. public function PaypalPay(Request $request, ShopProduct $shopProduct)
  64. {
  65. $request = new OrdersCreateRequest();
  66. $request->prefer('return=representation');
  67. $request->body = [
  68. "intent" => "CAPTURE",
  69. "purchase_units" => [
  70. [
  71. "reference_id" => uniqid(),
  72. "description" => $shopProduct->description,
  73. "amount" => [
  74. "value" => $shopProduct->getTotalPrice(),
  75. 'currency_code' => strtoupper($shopProduct->currency_code),
  76. 'breakdown' => [
  77. 'item_total' =>
  78. [
  79. 'currency_code' => strtoupper($shopProduct->currency_code),
  80. 'value' => $shopProduct->price,
  81. ],
  82. 'tax_total' =>
  83. [
  84. 'currency_code' => strtoupper($shopProduct->currency_code),
  85. 'value' => $shopProduct->getTaxValue(),
  86. ]
  87. ]
  88. ]
  89. ]
  90. ],
  91. "application_context" => [
  92. "cancel_url" => route('payment.Cancel'),
  93. "return_url" => route('payment.PaypalSuccess', ['product' => $shopProduct->id]),
  94. 'brand_name' => config('app.name', 'Laravel'),
  95. 'shipping_preference' => 'NO_SHIPPING'
  96. ]
  97. ];
  98. try {
  99. // Call API with your client and get a response for your call
  100. $response = $this->getPayPalClient()->execute($request);
  101. return redirect()->away($response->result->links[1]->href);
  102. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  103. } catch (HttpException $ex) {
  104. echo $ex->statusCode;
  105. dd(json_decode($ex->getMessage()));
  106. }
  107. }
  108. /**
  109. * @return PayPalHttpClient
  110. */
  111. protected function getPayPalClient()
  112. {
  113. $environment = env('APP_ENV') == 'local'
  114. ? new SandboxEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret())
  115. : new ProductionEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret());
  116. return new PayPalHttpClient($environment);
  117. }
  118. /**
  119. * @return string
  120. */
  121. protected function getPaypalClientId()
  122. {
  123. return env('APP_ENV') == 'local' ? config("SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID") : config("SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID");
  124. }
  125. /**
  126. * @return string
  127. */
  128. protected function getPaypalClientSecret()
  129. {
  130. return env('APP_ENV') == 'local' ? config("SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET") : config("SETTINGS::PAYMENTS:PAYPAL:SECRET");
  131. }
  132. /**
  133. * @param Request $laravelRequest
  134. */
  135. public function PaypalSuccess(Request $laravelRequest)
  136. {
  137. /** @var ShopProduct $shopProduct */
  138. $shopProduct = ShopProduct::findOrFail($laravelRequest->input('product'));
  139. /** @var User $user */
  140. $user = Auth::user();
  141. $request = new OrdersCaptureRequest($laravelRequest->input('token'));
  142. $request->prefer('return=representation');
  143. try {
  144. // Call API with your client and get a response for your call
  145. $response = $this->getPayPalClient()->execute($request);
  146. if ($response->statusCode == 201 || $response->statusCode == 200) {
  147. //update server limit
  148. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  149. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  150. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  151. }
  152. }
  153. //update User with bought item
  154. if ($shopProduct->type=="Credits") {
  155. $user->increment('credits', $shopProduct->quantity);
  156. }elseif ($shopProduct->type=="Server slots"){
  157. $user->increment('server_limit', $shopProduct->quantity);
  158. }
  159. //update role
  160. if ($user->role == 'member') {
  161. $user->update(['role' => 'client']);
  162. }
  163. //store payment
  164. $payment = Payment::create([
  165. 'user_id' => $user->id,
  166. 'payment_id' => $response->result->id,
  167. 'payment_method' => 'paypal',
  168. 'type' => $shopProduct->type,
  169. 'status' => 'paid',
  170. 'amount' => $shopProduct->quantity,
  171. 'price' => $shopProduct->price,
  172. 'tax_value' => $shopProduct->getTaxValue(),
  173. 'tax_percent' => $shopProduct->getTaxPercent(),
  174. 'total_price' => $shopProduct->getTotalPrice(),
  175. 'currency_code' => $shopProduct->currency_code,
  176. 'shop_item_product_id' => $shopProduct->id,
  177. ]);
  178. event(new UserUpdateCreditsEvent($user));
  179. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  180. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  181. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  182. }
  183. //redirect back to home
  184. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  185. }
  186. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  187. if (env('APP_ENV') == 'local') {
  188. dd($response);
  189. } else {
  190. abort(500);
  191. }
  192. } catch (HttpException $ex) {
  193. if (env('APP_ENV') == 'local') {
  194. echo $ex->statusCode;
  195. dd($ex->getMessage());
  196. } else {
  197. abort(422);
  198. }
  199. }
  200. }
  201. /**
  202. * @param Request $request
  203. */
  204. public function Cancel(Request $request)
  205. {
  206. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  207. }
  208. /**
  209. * @param Request $request
  210. * @param ShopProduct $shopProduct
  211. * @return RedirectResponse
  212. */
  213. public function StripePay(Request $request, ShopProduct $shopProduct)
  214. {
  215. $stripeClient = $this->getStripeClient();
  216. $request = $stripeClient->checkout->sessions->create([
  217. 'line_items' => [
  218. [
  219. 'price_data' => [
  220. 'currency' => $shopProduct->currency_code,
  221. 'product_data' => [
  222. 'name' => $shopProduct->display,
  223. 'description' => $shopProduct->description,
  224. ],
  225. 'unit_amount_decimal' => round($shopProduct->price * 100, 2),
  226. ],
  227. 'quantity' => 1,
  228. ],
  229. [
  230. 'price_data' => [
  231. 'currency' => $shopProduct->currency_code,
  232. 'product_data' => [
  233. 'name' => 'Product Tax',
  234. 'description' => $shopProduct->getTaxPercent() . "%",
  235. ],
  236. 'unit_amount_decimal' => round($shopProduct->getTaxValue(), 2) * 100,
  237. ],
  238. 'quantity' => 1,
  239. ]
  240. ],
  241. 'mode' => 'payment',
  242. "payment_method_types" => str_getcsv(config("SETTINGS::PAYMENTS:STRIPE:METHODS")),
  243. 'success_url' => route('payment.StripeSuccess', ['product' => $shopProduct->id]) . '&session_id={CHECKOUT_SESSION_ID}',
  244. 'cancel_url' => route('payment.Cancel'),
  245. ]);
  246. return redirect($request->url, 303);
  247. }
  248. /**
  249. * @param Request $request
  250. */
  251. public function StripeSuccess(Request $request)
  252. {
  253. /** @var ShopProduct $shopProduct */
  254. $shopProduct = ShopProduct::findOrFail($request->input('product'));
  255. /** @var User $user */
  256. $user = Auth::user();
  257. $stripeClient = $this->getStripeClient();
  258. try {
  259. //get stripe data
  260. $paymentSession = $stripeClient->checkout->sessions->retrieve($request->input('session_id'));
  261. $paymentIntent = $stripeClient->paymentIntents->retrieve($paymentSession->payment_intent);
  262. //get DB entry of this payment ID if existing
  263. $paymentDbEntry = Payment::where('payment_id', $paymentSession->payment_intent)->count();
  264. // check if payment is 100% completed and payment does not exist in db already
  265. if ($paymentSession->status == "complete" && $paymentIntent->status == "succeeded" && $paymentDbEntry == 0) {
  266. //update server limit
  267. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  268. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  269. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  270. }
  271. }
  272. //update User with bought item
  273. if ($shopProduct->type=="Credits") {
  274. $user->increment('credits', $shopProduct->quantity);
  275. }elseif ($shopProduct->type=="Server slots"){
  276. $user->increment('server_limit', $shopProduct->quantity);
  277. }
  278. //update role
  279. if ($user->role == 'member') {
  280. $user->update(['role' => 'client']);
  281. }
  282. //store paid payment
  283. $payment = Payment::create([
  284. 'user_id' => $user->id,
  285. 'payment_id' => $paymentSession->payment_intent,
  286. 'payment_method' => 'stripe',
  287. 'type' => $shopProduct->type,
  288. 'status' => 'paid',
  289. 'amount' => $shopProduct->quantity,
  290. 'price' => $shopProduct->price,
  291. 'tax_value' => $shopProduct->getTaxValue(),
  292. 'total_price' => $shopProduct->getTotalPrice(),
  293. 'tax_percent' => $shopProduct->getTaxPercent(),
  294. 'currency_code' => $shopProduct->currency_code,
  295. 'shop_item_product_id' => $shopProduct->id,
  296. ]);
  297. //payment notification
  298. $user->notify(new ConfirmPaymentNotification($payment));
  299. event(new UserUpdateCreditsEvent($user));
  300. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  301. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  302. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  303. }
  304. //redirect back to home
  305. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  306. } else {
  307. if ($paymentIntent->status == "processing") {
  308. //store processing payment
  309. $payment = Payment::create([
  310. 'user_id' => $user->id,
  311. 'payment_id' => $paymentSession->payment_intent,
  312. 'payment_method' => 'stripe',
  313. 'type' => $shopProduct->type,
  314. 'status' => 'processing',
  315. 'amount' => $shopProduct->quantity,
  316. 'price' => $shopProduct->price,
  317. 'tax_value' => $shopProduct->getTaxValue(),
  318. 'total_price' => $shopProduct->getTotalPrice(),
  319. 'tax_percent' => $shopProduct->getTaxPercent(),
  320. 'currency_code' => $shopProduct->currency_code,
  321. 'shop_item_product_id' => $shopProduct->id,
  322. ]);
  323. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  324. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  325. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  326. }
  327. //redirect back to home
  328. return redirect()->route('home')->with('success', __('Your payment is being processed!'));
  329. }
  330. if ($paymentDbEntry == 0 && $paymentIntent->status != "processing") {
  331. $stripeClient->paymentIntents->cancel($paymentIntent->id);
  332. //redirect back to home
  333. return redirect()->route('home')->with('success', __('Your payment has been canceled!'));
  334. } else {
  335. abort(402);
  336. }
  337. }
  338. } catch (HttpException $ex) {
  339. if (env('APP_ENV') == 'local') {
  340. echo $ex->statusCode;
  341. dd($ex->getMessage());
  342. } else {
  343. abort(422);
  344. }
  345. }
  346. }
  347. /**
  348. * @param Request $request
  349. */
  350. protected function handleStripePaymentSuccessHook($paymentIntent)
  351. {
  352. try {
  353. // Get payment db entry
  354. $payment = Payment::where('payment_id', $paymentIntent->id)->first();
  355. $user = User::where('id', $payment->user_id)->first();
  356. if ($paymentIntent->status == 'succeeded' && $payment->status == 'processing') {
  357. //update server limit
  358. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  359. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  360. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  361. }
  362. }
  363. //update User with bought item
  364. if ($shopProduct->type=="Credits") {
  365. $user->increment('credits', $shopProduct->quantity);
  366. }elseif ($shopProduct->type=="Server slots"){
  367. $user->increment('server_limit', $shopProduct->quantity);
  368. }
  369. //update role
  370. if ($user->role == 'member') {
  371. $user->update(['role' => 'client']);
  372. }
  373. //update payment db entry status
  374. $payment->update(['status' => 'paid']);
  375. //payment notification
  376. $user->notify(new ConfirmPaymentNotification($payment));
  377. event(new UserUpdateCreditsEvent($user));
  378. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  379. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  380. $this->createInvoice($user, $payment, 'paid', strtoupper($paymentIntent->currency));
  381. }
  382. }
  383. } catch (HttpException $ex) {
  384. abort(422);
  385. }
  386. }
  387. /**
  388. * @param Request $request
  389. */
  390. public function StripeWebhooks(Request $request)
  391. {
  392. \Stripe\Stripe::setApiKey($this->getStripeSecret());
  393. try {
  394. $payload = @file_get_contents('php://input');
  395. $sig_header = $request->header('Stripe-Signature');
  396. $event = null;
  397. $event = \Stripe\Webhook::constructEvent(
  398. $payload,
  399. $sig_header,
  400. $this->getStripeEndpointSecret()
  401. );
  402. } catch (\UnexpectedValueException $e) {
  403. // Invalid payload
  404. abort(400);
  405. } catch (\Stripe\Exception\SignatureVerificationException $e) {
  406. // Invalid signature
  407. abort(400);
  408. }
  409. // Handle the event
  410. switch ($event->type) {
  411. case 'payment_intent.succeeded':
  412. $paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
  413. $this->handleStripePaymentSuccessHook($paymentIntent);
  414. break;
  415. default:
  416. echo 'Received unknown event type ' . $event->type;
  417. }
  418. }
  419. /**
  420. * @return \Stripe\StripeClient
  421. */
  422. protected function getStripeClient()
  423. {
  424. return new \Stripe\StripeClient($this->getStripeSecret());
  425. }
  426. /**
  427. * @return string
  428. */
  429. protected function getStripeSecret()
  430. {
  431. return env('APP_ENV') == 'local'
  432. ? config("SETTINGS::PAYMENTS:STRIPE:TEST_SECRET")
  433. : config("SETTINGS::PAYMENTS:STRIPE:SECRET");
  434. }
  435. /**
  436. * @return string
  437. */
  438. protected function getStripeEndpointSecret()
  439. {
  440. return env('APP_ENV') == 'local'
  441. ? config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET")
  442. : config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET");
  443. }
  444. protected function createInvoice($user, $payment, $paymentStatus, $currencyCode)
  445. {
  446. $shopProduct = ShopProduct::where('id', $payment->shop_item_product_id)->first();
  447. //create invoice
  448. $lastInvoiceID = \App\Models\Invoice::where("invoice_name", "like", "%" . now()->format('mY') . "%")->count("id");
  449. $newInvoiceID = $lastInvoiceID + 1;
  450. $logoPath = storage_path('app/public/logo.png');
  451. $seller = new Party([
  452. 'name' => config("SETTINGS::INVOICE:COMPANY_NAME"),
  453. 'phone' => config("SETTINGS::INVOICE:COMPANY_PHONE"),
  454. 'address' => config("SETTINGS::INVOICE:COMPANY_ADDRESS"),
  455. 'vat' => config("SETTINGS::INVOICE:COMPANY_VAT"),
  456. 'custom_fields' => [
  457. 'E-Mail' => config("SETTINGS::INVOICE:COMPANY_MAIL"),
  458. "Web" => config("SETTINGS::INVOICE:COMPANY_WEBSITE")
  459. ],
  460. ]);
  461. $customer = new Buyer([
  462. 'name' => $user->name,
  463. 'custom_fields' => [
  464. 'E-Mail' => $user->email,
  465. 'Client ID' => $user->id,
  466. ],
  467. ]);
  468. $item = (new InvoiceItem())
  469. ->title($shopProduct->description)
  470. ->pricePerUnit($shopProduct->price);
  471. $notes = [
  472. __("Payment method") . ": " . $payment->payment_method,
  473. ];
  474. $notes = implode("<br>", $notes);
  475. $invoice = Invoice::make()
  476. ->template('controlpanel')
  477. ->name(__("Invoice"))
  478. ->buyer($customer)
  479. ->seller($seller)
  480. ->discountByPercent(0)
  481. ->taxRate(floatval($shopProduct->getTaxPercent()))
  482. ->shipping(0)
  483. ->addItem($item)
  484. ->status(__($paymentStatus))
  485. ->series(now()->format('mY'))
  486. ->delimiter("-")
  487. ->sequence($newInvoiceID)
  488. ->serialNumberFormat(config("SETTINGS::INVOICE:PREFIX") . '{DELIMITER}{SERIES}{SEQUENCE}')
  489. ->currencyCode($currencyCode)
  490. ->currencySymbol(Currencies::getSymbol($currencyCode))
  491. ->notes($notes);
  492. if (file_exists($logoPath)) {
  493. $invoice->logo($logoPath);
  494. }
  495. //Save the invoice in "storage\app\invoice\USER_ID\YEAR"
  496. $invoice->filename = $invoice->getSerialNumber() . '.pdf';
  497. $invoice->render();
  498. Storage::disk("local")->put("invoice/" . $user->id . "/" . now()->format('Y') . "/" . $invoice->filename, $invoice->output);
  499. \App\Models\Invoice::create([
  500. 'invoice_user' => $user->id,
  501. 'invoice_name' => $invoice->getSerialNumber(),
  502. 'payment_id' => $payment->payment_id,
  503. ]);
  504. //Send Invoice per Mail
  505. $user->notify(new InvoiceNotification($invoice, $user, $payment));
  506. }
  507. /**
  508. * @return JsonResponse|mixed
  509. * @throws Exception
  510. */
  511. public function dataTable()
  512. {
  513. $query = Payment::with('user');
  514. return datatables($query)
  515. ->editColumn('user', function (Payment $payment) {
  516. return $payment->user->name;
  517. })
  518. ->editColumn('price', function (Payment $payment) {
  519. return $payment->formatToCurrency($payment->price);
  520. })
  521. ->editColumn('tax_value', function (Payment $payment) {
  522. return $payment->formatToCurrency($payment->tax_value);
  523. })
  524. ->editColumn('tax_percent', function (Payment $payment) {
  525. return $payment->tax_percent . ' %';
  526. })
  527. ->editColumn('total_price', function (Payment $payment) {
  528. return $payment->formatToCurrency($payment->total_price);
  529. })
  530. ->editColumn('created_at', function (Payment $payment) {
  531. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  532. })
  533. ->addColumn('actions', function (Payment $payment) {
  534. return '<a data-content="' . __("Download") . '" data-toggle="popover" data-trigger="hover" data-placement="top" href="' . route('admin.invoices.downloadSingleInvoice', "id=" . $payment->payment_id) . '" class="btn btn-sm text-white btn-info mr-1"><i class="fas fa-file-download"></i></a>';
  535. })
  536. ->rawColumns(['actions'])
  537. ->make(true);
  538. }
  539. }