PaymentController.php 22 KB

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