PaymentController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Events\UserUpdateCreditsEvent;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\PartnerDiscount;
  6. use App\Models\Payment;
  7. use App\Models\User;
  8. use App\Models\ShopProduct;
  9. use App\Notifications\ConfirmPaymentNotification;
  10. use Exception;
  11. use Illuminate\Contracts\Foundation\Application;
  12. use Illuminate\Contracts\View\Factory;
  13. use Illuminate\Contracts\View\View;
  14. use Illuminate\Http\JsonResponse;
  15. use Illuminate\Http\RedirectResponse;
  16. use Illuminate\Http\Request;
  17. use Illuminate\Support\Facades\Auth;
  18. use Illuminate\Support\Facades\DB;
  19. use PayPalCheckoutSdk\Core\PayPalHttpClient;
  20. use PayPalCheckoutSdk\Core\ProductionEnvironment;
  21. use PayPalCheckoutSdk\Core\SandboxEnvironment;
  22. use PayPalHttp\HttpException;
  23. use Stripe\Stripe;
  24. use App\Helpers\ExtensionHelper;
  25. class PaymentController extends Controller
  26. {
  27. /**
  28. * @return Application|Factory|View
  29. */
  30. public function index()
  31. {
  32. return view('admin.payments.index')->with([
  33. 'payments' => Payment::paginate(15),
  34. ]);
  35. }
  36. /**
  37. * @param Request $request
  38. * @param ShopProduct $shopProduct
  39. * @return Application|Factory|View
  40. */
  41. public function checkOut(ShopProduct $shopProduct)
  42. {
  43. // get all payment gateway extensions
  44. $extensions = glob(app_path() . '/Extensions/PaymentGateways/*', GLOB_ONLYDIR);
  45. // 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
  46. $paymentGateways = [];
  47. foreach ($extensions as $extension) {
  48. $extensionName = basename($extension);
  49. $config = ExtensionHelper::getExtensionConfig($extensionName, 'PaymentGateways');
  50. if ($config) {
  51. $payment = new \stdClass();
  52. $payment->name = $config['name'];
  53. $payment->image = asset('images/Extensions/PaymentGateways/' . strtolower($extensionName) . '_logo.png');
  54. $paymentGateways[] = $payment;
  55. }
  56. }
  57. return view('store.checkout')->with([
  58. 'product' => $shopProduct,
  59. 'discountpercent' => PartnerDiscount::getDiscount(),
  60. 'discountvalue' => PartnerDiscount::getDiscount() * $shopProduct->price / 100,
  61. 'discountedprice' => $shopProduct->getPriceAfterDiscount(),
  62. 'taxvalue' => $shopProduct->getTaxValue(),
  63. 'taxpercent' => $shopProduct->getTaxPercent(),
  64. 'total' => $shopProduct->getTotalPrice(),
  65. 'paymentGateways' => $paymentGateways,
  66. ]);
  67. }
  68. /**
  69. * @param Request $request
  70. * @param ShopProduct $shopProduct
  71. * @return RedirectResponse
  72. */
  73. public function FreePay(ShopProduct $shopProduct)
  74. {
  75. //dd($shopProduct);
  76. //check if the product is really free or the discount is 100%
  77. if($shopProduct->getTotalPrice()>0) return redirect()->route('home')->with('error', __('An error ocured. Please try again.'));
  78. //give product
  79. /** @var User $user */
  80. $user = Auth::user();
  81. //not updating server limit
  82. //update User with bought item
  83. if ($shopProduct->type=="Credits") {
  84. $user->increment('credits', $shopProduct->quantity);
  85. }elseif ($shopProduct->type=="Server slots"){
  86. $user->increment('server_limit', $shopProduct->quantity);
  87. }
  88. //skipped the referral commission, because the user did not pay anything.
  89. //not giving client role
  90. //store payment
  91. $payment = Payment::create([
  92. 'user_id' => $user->id,
  93. 'payment_id' => uniqid(),
  94. 'payment_method' => 'free',
  95. 'type' => $shopProduct->type,
  96. 'status' => 'paid',
  97. 'amount' => $shopProduct->quantity,
  98. 'price' => $shopProduct->price - ($shopProduct->price*PartnerDiscount::getDiscount()/100),
  99. 'tax_value' => $shopProduct->getTaxValue(),
  100. 'tax_percent' => $shopProduct->getTaxPercent(),
  101. 'total_price' => $shopProduct->getTotalPrice(),
  102. 'currency_code' => $shopProduct->currency_code,
  103. 'shop_item_product_id' => $shopProduct->id,
  104. ]);
  105. event(new UserUpdateCreditsEvent($user));
  106. //not sending an invoice
  107. //redirect back to home
  108. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  109. }
  110. public function pay(Request $request)
  111. {
  112. $product = ShopProduct::find($request->product_id);
  113. $paymentGateway = $request->payment_method;
  114. return redirect()->route('payment.' . $paymentGateway . 'Pay', ['shopProduct' => $product->id]);
  115. }
  116. /**
  117. * @param Request $request
  118. */
  119. public function Cancel(Request $request)
  120. {
  121. return redirect()->route('store.index')->with('info', 'Payment was Canceled');
  122. }
  123. /**
  124. * @param Request $request
  125. * @param ShopProduct $shopProduct
  126. * @return RedirectResponse
  127. */
  128. public function StripePay(Request $request, ShopProduct $shopProduct)
  129. {
  130. if(!$this->checkAmount($shopProduct->getTotalPrice(), strtoupper($shopProduct->currency_code), "stripe")) return redirect()->route('home')->with('error', __('The product you chose can´t be purchased with this payment method. The total amount is too small. Please buy a bigger amount or try a different payment method.'));
  131. $stripeClient = $this->getStripeClient();
  132. $request = $stripeClient->checkout->sessions->create([
  133. 'line_items' => [
  134. [
  135. 'price_data' => [
  136. 'currency' => $shopProduct->currency_code,
  137. 'product_data' => [
  138. 'name' => $shopProduct->display.(PartnerDiscount::getDiscount() ? (' ('.__('Discount').' '.PartnerDiscount::getDiscount().'%)') : ''),
  139. 'description' => $shopProduct->description,
  140. ],
  141. 'unit_amount_decimal' => round($shopProduct->getPriceAfterDiscount() * 100, 2),
  142. ],
  143. 'quantity' => 1,
  144. ],
  145. [
  146. 'price_data' => [
  147. 'currency' => $shopProduct->currency_code,
  148. 'product_data' => [
  149. 'name' => __('Tax'),
  150. 'description' => $shopProduct->getTaxPercent().'%',
  151. ],
  152. 'unit_amount_decimal' => round($shopProduct->getTaxValue(), 2) * 100,
  153. ],
  154. 'quantity' => 1,
  155. ],
  156. ],
  157. 'mode' => 'payment',
  158. 'payment_method_types' => str_getcsv(config('SETTINGS::PAYMENTS:STRIPE:METHODS')),
  159. 'success_url' => route('payment.StripeSuccess', ['product' => $shopProduct->id]).'&session_id={CHECKOUT_SESSION_ID}',
  160. 'cancel_url' => route('payment.Cancel'),
  161. ]);
  162. return redirect($request->url, 303);
  163. }
  164. /**
  165. * @param Request $request
  166. */
  167. public function StripeSuccess(Request $request)
  168. {
  169. /** @var ShopProduct $shopProduct */
  170. $shopProduct = ShopProduct::findOrFail($request->input('product'));
  171. /** @var User $user */
  172. $user = Auth::user();
  173. $stripeClient = $this->getStripeClient();
  174. try {
  175. //get stripe data
  176. $paymentSession = $stripeClient->checkout->sessions->retrieve($request->input('session_id'));
  177. $paymentIntent = $stripeClient->paymentIntents->retrieve($paymentSession->payment_intent);
  178. //get DB entry of this payment ID if existing
  179. $paymentDbEntry = Payment::where('payment_id', $paymentSession->payment_intent)->count();
  180. // check if payment is 100% completed and payment does not exist in db already
  181. if ($paymentSession->status == 'complete' && $paymentIntent->status == 'succeeded' && $paymentDbEntry == 0) {
  182. //update server limit
  183. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  184. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  185. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  186. }
  187. }
  188. //update User with bought item
  189. if ($shopProduct->type == 'Credits') {
  190. $user->increment('credits', $shopProduct->quantity);
  191. } elseif ($shopProduct->type == 'Server slots') {
  192. $user->increment('server_limit', $shopProduct->quantity);
  193. }
  194. //update role give Referral-reward
  195. if ($user->role == 'member') {
  196. $user->update(['role' => 'client']);
  197. if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits') {
  198. if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) {
  199. $ref_user = User::findOrFail($ref_user->referral_id);
  200. $increment = number_format($shopProduct->quantity / 100 * config('SETTINGS::REFERRAL:PERCENTAGE'), 0, '', '');
  201. $ref_user->increment('credits', $increment);
  202. //LOGS REFERRALS IN THE ACTIVITY LOG
  203. activity()
  204. ->performedOn($user)
  205. ->causedBy($ref_user)
  206. ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  207. }
  208. }
  209. }
  210. //store paid payment
  211. $payment = Payment::create([
  212. 'user_id' => $user->id,
  213. 'payment_id' => $paymentSession->payment_intent,
  214. 'payment_method' => 'stripe',
  215. 'type' => $shopProduct->type,
  216. 'status' => 'paid',
  217. 'amount' => $shopProduct->quantity,
  218. 'price' => $shopProduct->price - ($shopProduct->price * PartnerDiscount::getDiscount() / 100),
  219. 'tax_value' => $shopProduct->getTaxValue(),
  220. 'total_price' => $shopProduct->getTotalPrice(),
  221. 'tax_percent' => $shopProduct->getTaxPercent(),
  222. 'currency_code' => $shopProduct->currency_code,
  223. 'shop_item_product_id' => $shopProduct->id,
  224. ]);
  225. //payment notification
  226. $user->notify(new ConfirmPaymentNotification($payment));
  227. event(new UserUpdateCreditsEvent($user));
  228. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  229. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  230. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  231. }
  232. //redirect back to home
  233. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  234. } else {
  235. if ($paymentIntent->status == 'processing') {
  236. //store processing payment
  237. $payment = Payment::create([
  238. 'user_id' => $user->id,
  239. 'payment_id' => $paymentSession->payment_intent,
  240. 'payment_method' => 'stripe',
  241. 'type' => $shopProduct->type,
  242. 'status' => 'processing',
  243. 'amount' => $shopProduct->quantity,
  244. 'price' => $shopProduct->price,
  245. 'tax_value' => $shopProduct->getTaxValue(),
  246. 'total_price' => $shopProduct->getTotalPrice(),
  247. 'tax_percent' => $shopProduct->getTaxPercent(),
  248. 'currency_code' => $shopProduct->currency_code,
  249. 'shop_item_product_id' => $shopProduct->id,
  250. ]);
  251. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  252. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  253. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  254. }
  255. //redirect back to home
  256. return redirect()->route('home')->with('success', __('Your payment is being processed!'));
  257. }
  258. if ($paymentDbEntry == 0 && $paymentIntent->status != 'processing') {
  259. $stripeClient->paymentIntents->cancel($paymentIntent->id);
  260. //redirect back to home
  261. return redirect()->route('home')->with('success', __('Your payment has been canceled!'));
  262. } else {
  263. abort(402);
  264. }
  265. }
  266. } catch (HttpException $ex) {
  267. if (env('APP_ENV') == 'local') {
  268. echo $ex->statusCode;
  269. dd($ex->getMessage());
  270. } else {
  271. abort(422);
  272. }
  273. }
  274. }
  275. /**
  276. * @param Request $request
  277. */
  278. protected function handleStripePaymentSuccessHook($paymentIntent)
  279. {
  280. try {
  281. // Get payment db entry
  282. $payment = Payment::where('payment_id', $paymentIntent->id)->first();
  283. $user = User::where('id', $payment->user_id)->first();
  284. if ($paymentIntent->status == 'succeeded' && $payment->status == 'processing') {
  285. //update server limit
  286. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  287. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  288. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  289. }
  290. }
  291. //update User with bought item
  292. if ($shopProduct->type == 'Credits') {
  293. $user->increment('credits', $shopProduct->quantity);
  294. } elseif ($shopProduct->type == 'Server slots') {
  295. $user->increment('server_limit', $shopProduct->quantity);
  296. }
  297. //update role give Referral-reward
  298. if ($user->role == 'member') {
  299. $user->update(['role' => 'client']);
  300. if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits') {
  301. if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) {
  302. $ref_user = User::findOrFail($ref_user->referral_id);
  303. $increment = number_format($shopProduct->quantity / 100 * config('SETTINGS::REFERRAL:PERCENTAGE'), 0, '', '');
  304. $ref_user->increment('credits', $increment);
  305. //LOGS REFERRALS IN THE ACTIVITY LOG
  306. activity()
  307. ->performedOn($user)
  308. ->causedBy($ref_user)
  309. ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  310. }
  311. }
  312. }
  313. //update payment db entry status
  314. $payment->update(['status' => 'paid']);
  315. //payment notification
  316. $user->notify(new ConfirmPaymentNotification($payment));
  317. event(new UserUpdateCreditsEvent($user));
  318. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  319. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  320. $this->createInvoice($user, $payment, 'paid', strtoupper($paymentIntent->currency));
  321. }
  322. }
  323. } catch (HttpException $ex) {
  324. abort(422);
  325. }
  326. }
  327. /**
  328. * @param Request $request
  329. */
  330. public function StripeWebhooks(Request $request)
  331. {
  332. \Stripe\Stripe::setApiKey($this->getStripeSecret());
  333. try {
  334. $payload = @file_get_contents('php://input');
  335. $sig_header = $request->header('Stripe-Signature');
  336. $event = null;
  337. $event = \Stripe\Webhook::constructEvent(
  338. $payload,
  339. $sig_header,
  340. $this->getStripeEndpointSecret()
  341. );
  342. } catch (\UnexpectedValueException $e) {
  343. // Invalid payload
  344. abort(400);
  345. } catch (\Stripe\Exception\SignatureVerificationException $e) {
  346. // Invalid signature
  347. abort(400);
  348. }
  349. // Handle the event
  350. switch ($event->type) {
  351. case 'payment_intent.succeeded':
  352. $paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
  353. $this->handleStripePaymentSuccessHook($paymentIntent);
  354. break;
  355. default:
  356. echo 'Received unknown event type '.$event->type;
  357. }
  358. }
  359. /**
  360. * @return \Stripe\StripeClient
  361. */
  362. protected function getStripeClient()
  363. {
  364. return new \Stripe\StripeClient($this->getStripeSecret());
  365. }
  366. /**
  367. * @return string
  368. */
  369. protected function getStripeSecret()
  370. {
  371. return env('APP_ENV') == 'local'
  372. ? config('SETTINGS::PAYMENTS:STRIPE:TEST_SECRET')
  373. : config('SETTINGS::PAYMENTS:STRIPE:SECRET');
  374. }
  375. /**
  376. * @return string
  377. */
  378. protected function getStripeEndpointSecret()
  379. {
  380. return env('APP_ENV') == 'local'
  381. ? config('SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET')
  382. : config('SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET');
  383. }
  384. public function checkAmount($amount, $currencyCode, $payment_method)
  385. {
  386. $minimums = [
  387. "USD" => [
  388. "paypal" => 0,
  389. "stripe" => 0.5
  390. ],
  391. "AED" => [
  392. "paypal" => 0,
  393. "stripe" => 2
  394. ],
  395. "AUD" => [
  396. "paypal" => 0,
  397. "stripe" => 0.5
  398. ],
  399. "BGN" => [
  400. "paypal" => 0,
  401. "stripe" => 1
  402. ],
  403. "BRL" => [
  404. "paypal" => 0,
  405. "stripe" => 0.5
  406. ],
  407. "CAD" => [
  408. "paypal" => 0,
  409. "stripe" => 0.5
  410. ],
  411. "CHF" => [
  412. "paypal" => 0,
  413. "stripe" => 0.5
  414. ],
  415. "CZK" => [
  416. "paypal" => 0,
  417. "stripe" => 15
  418. ],
  419. "DKK" => [
  420. "paypal" => 0,
  421. "stripe" => 2.5
  422. ],
  423. "EUR" => [
  424. "paypal" => 0,
  425. "stripe" => 0.5
  426. ],
  427. "GBP" => [
  428. "paypal" => 0,
  429. "stripe" => 0.3
  430. ],
  431. "HKD" => [
  432. "paypal" => 0,
  433. "stripe" => 4
  434. ],
  435. "HRK" => [
  436. "paypal" => 0,
  437. "stripe" => 0.5
  438. ],
  439. "HUF" => [
  440. "paypal" => 0,
  441. "stripe" => 175
  442. ],
  443. "INR" => [
  444. "paypal" => 0,
  445. "stripe" => 0.5
  446. ],
  447. "JPY" => [
  448. "paypal" => 0,
  449. "stripe" => 0.5
  450. ],
  451. "MXN" => [
  452. "paypal" => 0,
  453. "stripe" => 10
  454. ],
  455. "MYR" => [
  456. "paypal" => 0,
  457. "stripe" => 2
  458. ],
  459. "NOK" => [
  460. "paypal" => 0,
  461. "stripe" => 3
  462. ],
  463. "NZD" => [
  464. "paypal" => 0,
  465. "stripe" => 0.5
  466. ],
  467. "PLN" => [
  468. "paypal" => 0,
  469. "stripe" => 2
  470. ],
  471. "RON" => [
  472. "paypal" => 0,
  473. "stripe" => 2
  474. ],
  475. "SEK" => [
  476. "paypal" => 0,
  477. "stripe" => 3
  478. ],
  479. "SGD" => [
  480. "paypal" => 0,
  481. "stripe" => 0.5
  482. ],
  483. "THB" => [
  484. "paypal" => 0,
  485. "stripe" => 10
  486. ]
  487. ];
  488. return $amount >= $minimums[$currencyCode][$payment_method];
  489. }
  490. /**
  491. * @return JsonResponse|mixed
  492. *
  493. * @throws Exception
  494. */
  495. public function dataTable()
  496. {
  497. $query = Payment::with('user');
  498. return datatables($query)
  499. ->addColumn('user', function (Payment $payment) {
  500. return
  501. ($payment->user)?'<a href="'.route('admin.users.show', $payment->user->id).'">'.$payment->user->name.'</a>':__('Unknown user');
  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 ['display' => $payment->created_at ? $payment->created_at->diffForHumans() : '',
  517. 'raw' => $payment->created_at ? strtotime($payment->created_at) : ''];
  518. })
  519. ->addColumn('actions', function (Payment $payment) {
  520. 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>';
  521. })
  522. ->rawColumns(['actions', 'user'])
  523. ->make(true);
  524. }
  525. }