PaymentController.php 22 KB

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