PaymentController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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\PartnerDiscount;
  7. use App\Models\Payment;
  8. use App\Models\ShopProduct;
  9. use App\Models\Settings;
  10. use App\Models\User;
  11. use App\Notifications\InvoiceNotification;
  12. use App\Notifications\ConfirmPaymentNotification;
  13. use Exception;
  14. use Illuminate\Contracts\Foundation\Application;
  15. use Illuminate\Contracts\View\Factory;
  16. use Illuminate\Contracts\View\View;
  17. use Illuminate\Http\JsonResponse;
  18. use Illuminate\Http\RedirectResponse;
  19. use Illuminate\Http\Request;
  20. use Illuminate\Support\Facades\Auth;
  21. use Illuminate\Support\Facades\DB;
  22. use Illuminate\Support\Facades\Log;
  23. use Illuminate\Support\Facades\Storage;
  24. use LaravelDaily\Invoices\Classes\Buyer;
  25. use LaravelDaily\Invoices\Classes\InvoiceItem;
  26. use LaravelDaily\Invoices\Classes\Party;
  27. use LaravelDaily\Invoices\Invoice;
  28. use PayPalCheckoutSdk\Core\PayPalHttpClient;
  29. use PayPalCheckoutSdk\Core\ProductionEnvironment;
  30. use PayPalCheckoutSdk\Core\SandboxEnvironment;
  31. use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
  32. use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
  33. use PayPalHttp\HttpException;
  34. use Stripe\Stripe;
  35. use Symfony\Component\Intl\Currencies;
  36. use App\Helpers\ExtensionHelper;
  37. class PaymentController extends Controller
  38. {
  39. /**
  40. * @return Application|Factory|View
  41. */
  42. public function index()
  43. {
  44. return view('admin.payments.index')->with([
  45. 'payments' => Payment::paginate(15)
  46. ]);
  47. }
  48. /**
  49. * @param Request $request
  50. * @param ShopProduct $shopProduct
  51. * @return Application|Factory|View
  52. */
  53. public function checkOut(Request $request, ShopProduct $shopProduct)
  54. {
  55. // get all payment gateway extensions
  56. $extensions = glob(app_path() . '/Extensions/PaymentGateways/*', GLOB_ONLYDIR);
  57. // build a paymentgateways array that contains the routes for the payment gateways and the image path for the payment gateway which lays in public/images/Extensions/PaymentGateways with the extensionname in lowercase
  58. $paymentGateways = [];
  59. foreach ($extensions as $extension) {
  60. $extensionName = basename($extension);
  61. $config = ExtensionHelper::getExtensionConfig($extensionName, 'PaymentGateways');
  62. if ($config) {
  63. $payment = new \stdClass();
  64. $payment->name = $config['name'];
  65. $payment->image = asset('images/Extensions/PaymentGateways/' . strtolower($extensionName) . '_logo.png');
  66. $paymentGateways[] = $payment;
  67. }
  68. }
  69. return view('store.checkout')->with([
  70. 'product' => $shopProduct,
  71. 'discountpercent' => PartnerDiscount::getDiscount(),
  72. 'discountvalue' => PartnerDiscount::getDiscount() * $shopProduct->price/100,
  73. 'discountedprice' => $shopProduct->getPriceAfterDiscount(),
  74. 'taxvalue' => $shopProduct->getTaxValue(),
  75. 'taxpercent' => $shopProduct->getTaxPercent(),
  76. 'total' => $shopProduct->getTotalPrice(),
  77. 'paymentGateways' => $paymentGateways,
  78. ]);
  79. }
  80. public function pay(Request $request)
  81. {
  82. $product = ShopProduct::find($request->product_id);
  83. $paymentGateway = $request->payment_method;
  84. return redirect()->route('payment.' . $paymentGateway . 'Pay', ['shopProduct' => $product->id]);
  85. }
  86. /**
  87. * @param Request $request
  88. */
  89. public function Cancel(Request $request)
  90. {
  91. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  92. }
  93. /**
  94. * @param Request $request
  95. * @param ShopProduct $shopProduct
  96. * @return RedirectResponse
  97. */
  98. public function StripePay(Request $request, ShopProduct $shopProduct)
  99. {
  100. $stripeClient = $this->getStripeClient();
  101. $request = $stripeClient->checkout->sessions->create([
  102. 'line_items' => [
  103. [
  104. 'price_data' => [
  105. 'currency' => $shopProduct->currency_code,
  106. 'product_data' => [
  107. 'name' => $shopProduct->display . (PartnerDiscount::getDiscount()?(" (" . __('Discount') . " " . PartnerDiscount::getDiscount() . '%)'):""),
  108. 'description' => $shopProduct->description,
  109. ],
  110. 'unit_amount_decimal' => round($shopProduct->getPriceAfterDiscount() * 100, 2),
  111. ],
  112. 'quantity' => 1,
  113. ],
  114. [
  115. 'price_data' => [
  116. 'currency' => $shopProduct->currency_code,
  117. 'product_data' => [
  118. 'name' => __('Tax'),
  119. 'description' => $shopProduct->getTaxPercent() . "%",
  120. ],
  121. 'unit_amount_decimal' => round($shopProduct->getTaxValue(), 2) * 100,
  122. ],
  123. 'quantity' => 1,
  124. ]
  125. ],
  126. 'mode' => 'payment',
  127. "payment_method_types" => str_getcsv(config("SETTINGS::PAYMENTS:STRIPE:METHODS")),
  128. 'success_url' => route('payment.StripeSuccess', ['product' => $shopProduct->id]) . '&session_id={CHECKOUT_SESSION_ID}',
  129. 'cancel_url' => route('payment.Cancel'),
  130. ]);
  131. return redirect($request->url, 303);
  132. }
  133. /**
  134. * @param Request $request
  135. */
  136. public function StripeSuccess(Request $request)
  137. {
  138. /** @var ShopProduct $shopProduct */
  139. $shopProduct = ShopProduct::findOrFail($request->input('product'));
  140. /** @var User $user */
  141. $user = Auth::user();
  142. $stripeClient = $this->getStripeClient();
  143. try {
  144. //get stripe data
  145. $paymentSession = $stripeClient->checkout->sessions->retrieve($request->input('session_id'));
  146. $paymentIntent = $stripeClient->paymentIntents->retrieve($paymentSession->payment_intent);
  147. //get DB entry of this payment ID if existing
  148. $paymentDbEntry = Payment::where('payment_id', $paymentSession->payment_intent)->count();
  149. // check if payment is 100% completed and payment does not exist in db already
  150. if ($paymentSession->status == "complete" && $paymentIntent->status == "succeeded" && $paymentDbEntry == 0) {
  151. //update server limit
  152. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  153. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  154. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  155. }
  156. }
  157. //update User with bought item
  158. if ($shopProduct->type=="Credits") {
  159. $user->increment('credits', $shopProduct->quantity);
  160. }elseif ($shopProduct->type=="Server slots"){
  161. $user->increment('server_limit', $shopProduct->quantity);
  162. }
  163. //update role give Referral-reward
  164. if ($user->role == 'member') {
  165. $user->update(['role' => 'client']);
  166. if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE") == "both") && $shopProduct->type=="Credits"){
  167. if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){
  168. $ref_user = User::findOrFail($ref_user->referral_id);
  169. $increment = number_format($shopProduct->quantity/100*config("SETTINGS::REFERRAL:PERCENTAGE"),0,"","");
  170. $ref_user->increment('credits', $increment);
  171. //LOGS REFERRALS IN THE ACTIVITY LOG
  172. activity()
  173. ->performedOn($user)
  174. ->causedBy($ref_user)
  175. ->log('gained '. $increment.' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  176. }
  177. }
  178. }
  179. //store paid payment
  180. $payment = Payment::create([
  181. 'user_id' => $user->id,
  182. 'payment_id' => $paymentSession->payment_intent,
  183. 'payment_method' => 'stripe',
  184. 'type' => $shopProduct->type,
  185. 'status' => 'paid',
  186. 'amount' => $shopProduct->quantity,
  187. 'price' => $shopProduct->price - ($shopProduct->price*PartnerDiscount::getDiscount()/100),
  188. 'tax_value' => $shopProduct->getTaxValue(),
  189. 'total_price' => $shopProduct->getTotalPrice(),
  190. 'tax_percent' => $shopProduct->getTaxPercent(),
  191. 'currency_code' => $shopProduct->currency_code,
  192. 'shop_item_product_id' => $shopProduct->id,
  193. ]);
  194. //payment notification
  195. $user->notify(new ConfirmPaymentNotification($payment));
  196. event(new UserUpdateCreditsEvent($user));
  197. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  198. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  199. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  200. }
  201. //redirect back to home
  202. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  203. } else {
  204. if ($paymentIntent->status == "processing") {
  205. //store processing payment
  206. $payment = Payment::create([
  207. 'user_id' => $user->id,
  208. 'payment_id' => $paymentSession->payment_intent,
  209. 'payment_method' => 'stripe',
  210. 'type' => $shopProduct->type,
  211. 'status' => 'processing',
  212. 'amount' => $shopProduct->quantity,
  213. 'price' => $shopProduct->price,
  214. 'tax_value' => $shopProduct->getTaxValue(),
  215. 'total_price' => $shopProduct->getTotalPrice(),
  216. 'tax_percent' => $shopProduct->getTaxPercent(),
  217. 'currency_code' => $shopProduct->currency_code,
  218. 'shop_item_product_id' => $shopProduct->id,
  219. ]);
  220. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  221. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  222. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  223. }
  224. //redirect back to home
  225. return redirect()->route('home')->with('success', __('Your payment is being processed!'));
  226. }
  227. if ($paymentDbEntry == 0 && $paymentIntent->status != "processing") {
  228. $stripeClient->paymentIntents->cancel($paymentIntent->id);
  229. //redirect back to home
  230. return redirect()->route('home')->with('success', __('Your payment has been canceled!'));
  231. } else {
  232. abort(402);
  233. }
  234. }
  235. } catch (HttpException $ex) {
  236. if (env('APP_ENV') == 'local') {
  237. echo $ex->statusCode;
  238. dd($ex->getMessage());
  239. } else {
  240. abort(422);
  241. }
  242. }
  243. }
  244. /**
  245. * @param Request $request
  246. */
  247. protected function handleStripePaymentSuccessHook($paymentIntent)
  248. {
  249. try {
  250. // Get payment db entry
  251. $payment = Payment::where('payment_id', $paymentIntent->id)->first();
  252. $user = User::where('id', $payment->user_id)->first();
  253. if ($paymentIntent->status == 'succeeded' && $payment->status == 'processing') {
  254. //update server limit
  255. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  256. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  257. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  258. }
  259. }
  260. //update User with bought item
  261. if ($shopProduct->type=="Credits") {
  262. $user->increment('credits', $shopProduct->quantity);
  263. }elseif ($shopProduct->type=="Server slots"){
  264. $user->increment('server_limit', $shopProduct->quantity);
  265. }
  266. //update role give Referral-reward
  267. if ($user->role == 'member') {
  268. $user->update(['role' => 'client']);
  269. if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE") == "both")&& $shopProduct->type=="Credits"){
  270. if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){
  271. $ref_user = User::findOrFail($ref_user->referral_id);
  272. $increment = number_format($shopProduct->quantity/100*config("SETTINGS::REFERRAL:PERCENTAGE"),0,"","");
  273. $ref_user->increment('credits', $increment);
  274. //LOGS REFERRALS IN THE ACTIVITY LOG
  275. activity()
  276. ->performedOn($user)
  277. ->causedBy($ref_user)
  278. ->log('gained '. $increment.' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  279. }
  280. }
  281. }
  282. //update payment db entry status
  283. $payment->update(['status' => 'paid']);
  284. //payment notification
  285. $user->notify(new ConfirmPaymentNotification($payment));
  286. event(new UserUpdateCreditsEvent($user));
  287. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  288. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  289. $this->createInvoice($user, $payment, 'paid', strtoupper($paymentIntent->currency));
  290. }
  291. }
  292. } catch (HttpException $ex) {
  293. abort(422);
  294. }
  295. }
  296. /**
  297. * @param Request $request
  298. */
  299. public function StripeWebhooks(Request $request)
  300. {
  301. \Stripe\Stripe::setApiKey($this->getStripeSecret());
  302. try {
  303. $payload = @file_get_contents('php://input');
  304. $sig_header = $request->header('Stripe-Signature');
  305. $event = null;
  306. $event = \Stripe\Webhook::constructEvent(
  307. $payload,
  308. $sig_header,
  309. $this->getStripeEndpointSecret()
  310. );
  311. } catch (\UnexpectedValueException $e) {
  312. // Invalid payload
  313. abort(400);
  314. } catch (\Stripe\Exception\SignatureVerificationException $e) {
  315. // Invalid signature
  316. abort(400);
  317. }
  318. // Handle the event
  319. switch ($event->type) {
  320. case 'payment_intent.succeeded':
  321. $paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
  322. $this->handleStripePaymentSuccessHook($paymentIntent);
  323. break;
  324. default:
  325. echo 'Received unknown event type ' . $event->type;
  326. }
  327. }
  328. /**
  329. * @return \Stripe\StripeClient
  330. */
  331. protected function getStripeClient()
  332. {
  333. return new \Stripe\StripeClient($this->getStripeSecret());
  334. }
  335. /**
  336. * @return string
  337. */
  338. protected function getStripeSecret()
  339. {
  340. return env('APP_ENV') == 'local'
  341. ? config("SETTINGS::PAYMENTS:STRIPE:TEST_SECRET")
  342. : config("SETTINGS::PAYMENTS:STRIPE:SECRET");
  343. }
  344. /**
  345. * @return string
  346. */
  347. protected function getStripeEndpointSecret()
  348. {
  349. return env('APP_ENV') == 'local'
  350. ? config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET")
  351. : config("SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET");
  352. }
  353. protected function createInvoice($user, $payment, $paymentStatus, $currencyCode)
  354. {
  355. $shopProduct = ShopProduct::where('id', $payment->shop_item_product_id)->first();
  356. //create invoice
  357. $lastInvoiceID = \App\Models\Invoice::where("invoice_name", "like", "%" . now()->format('mY') . "%")->count("id");
  358. $newInvoiceID = $lastInvoiceID + 1;
  359. $logoPath = storage_path('app/public/logo.png');
  360. $seller = new Party([
  361. 'name' => config("SETTINGS::INVOICE:COMPANY_NAME"),
  362. 'phone' => config("SETTINGS::INVOICE:COMPANY_PHONE"),
  363. 'address' => config("SETTINGS::INVOICE:COMPANY_ADDRESS"),
  364. 'vat' => config("SETTINGS::INVOICE:COMPANY_VAT"),
  365. 'custom_fields' => [
  366. 'E-Mail' => config("SETTINGS::INVOICE:COMPANY_MAIL"),
  367. "Web" => config("SETTINGS::INVOICE:COMPANY_WEBSITE")
  368. ],
  369. ]);
  370. $customer = new Buyer([
  371. 'name' => $user->name,
  372. 'custom_fields' => [
  373. 'E-Mail' => $user->email,
  374. 'Client ID' => $user->id,
  375. ],
  376. ]);
  377. $item = (new InvoiceItem())
  378. ->title($shopProduct->description)
  379. ->pricePerUnit($shopProduct->price);
  380. $notes = [
  381. __("Payment method") . ": " . $payment->payment_method,
  382. ];
  383. $notes = implode("<br>", $notes);
  384. $invoice = Invoice::make()
  385. ->template('controlpanel')
  386. ->name(__("Invoice"))
  387. ->buyer($customer)
  388. ->seller($seller)
  389. ->discountByPercent(PartnerDiscount::getDiscount())
  390. ->taxRate(floatval($shopProduct->getTaxPercent()))
  391. ->shipping(0)
  392. ->addItem($item)
  393. ->status(__($paymentStatus))
  394. ->series(now()->format('mY'))
  395. ->delimiter("-")
  396. ->sequence($newInvoiceID)
  397. ->serialNumberFormat(config("SETTINGS::INVOICE:PREFIX") . '{DELIMITER}{SERIES}{SEQUENCE}')
  398. ->currencyCode($currencyCode)
  399. ->currencySymbol(Currencies::getSymbol($currencyCode))
  400. ->notes($notes);
  401. if (file_exists($logoPath)) {
  402. $invoice->logo($logoPath);
  403. }
  404. //Save the invoice in "storage\app\invoice\USER_ID\YEAR"
  405. $invoice->filename = $invoice->getSerialNumber() . '.pdf';
  406. $invoice->render();
  407. Storage::disk("local")->put("invoice/" . $user->id . "/" . now()->format('Y') . "/" . $invoice->filename, $invoice->output);
  408. \App\Models\Invoice::create([
  409. 'invoice_user' => $user->id,
  410. 'invoice_name' => $invoice->getSerialNumber(),
  411. 'payment_id' => $payment->payment_id,
  412. ]);
  413. //Send Invoice per Mail
  414. $user->notify(new InvoiceNotification($invoice, $user, $payment));
  415. }
  416. /**
  417. * @return JsonResponse|mixed
  418. * @throws Exception
  419. */
  420. public function dataTable()
  421. {
  422. $query = Payment::with('user');
  423. return datatables($query)
  424. ->editColumn('user', function (Payment $payment) {
  425. return
  426. ($payment->user)?'<a href="'.route('admin.users.show', $payment->user->id).'">'.$payment->user->name.'</a>':__('Unknown user');
  427. })
  428. ->editColumn('price', function (Payment $payment) {
  429. return $payment->formatToCurrency($payment->price);
  430. })
  431. ->editColumn('tax_value', function (Payment $payment) {
  432. return $payment->formatToCurrency($payment->tax_value);
  433. })
  434. ->editColumn('tax_percent', function (Payment $payment) {
  435. return $payment->tax_percent . ' %';
  436. })
  437. ->editColumn('total_price', function (Payment $payment) {
  438. return $payment->formatToCurrency($payment->total_price);
  439. })
  440. ->editColumn('created_at', function (Payment $payment) {
  441. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  442. })
  443. ->addColumn('actions', function (Payment $payment) {
  444. 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>';
  445. })
  446. ->rawColumns(['actions', 'user'])
  447. ->make(true);
  448. }
  449. }