PaymentController.php 21 KB

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