PaymentController.php 23 KB

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