PaymentController.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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\ShopProduct;
  8. use App\Models\User;
  9. use App\Notifications\ConfirmPaymentNotification;
  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\DB;
  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 Symfony\Component\Intl\Currencies;
  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 ShopProduct $shopProduct
  46. * @return Application|Factory|View
  47. */
  48. public function checkOut(Request $request, ShopProduct $shopProduct)
  49. {
  50. return view('store.checkout')->with([
  51. 'product' => $shopProduct,
  52. 'discountpercent' => PartnerDiscount::getDiscount(),
  53. 'discountvalue' => PartnerDiscount::getDiscount() * $shopProduct->price / 100,
  54. 'discountedprice' => $shopProduct->getPriceAfterDiscount(),
  55. 'taxvalue' => $shopProduct->getTaxValue(),
  56. 'taxpercent' => $shopProduct->getTaxPercent(),
  57. 'total' => $shopProduct->getTotalPrice(),
  58. ]);
  59. }
  60. /**
  61. * @param Request $request
  62. * @param ShopProduct $shopProduct
  63. * @return RedirectResponse
  64. */
  65. public function FreePay(Request $request, ShopProduct $shopProduct)
  66. {
  67. //dd($shopProduct);
  68. //check if the product is really free or the discount is 100%
  69. if($shopProduct->getTotalPrice()>0) return redirect()->route('home')->with('error', __('An error ocured. Please try again.'));
  70. //give product
  71. /** @var User $user */
  72. $user = Auth::user();
  73. //not updating server limit
  74. //update User with bought item
  75. if ($shopProduct->type=="Credits") {
  76. $user->increment('credits', $shopProduct->quantity);
  77. }elseif ($shopProduct->type=="Server slots"){
  78. $user->increment('server_limit', $shopProduct->quantity);
  79. }
  80. //skipped the referral commission, because the user did not pay anything.
  81. //not giving client role
  82. //store payment
  83. $payment = Payment::create([
  84. 'user_id' => $user->id,
  85. 'payment_id' => uniqid(),
  86. 'payment_method' => 'free',
  87. 'type' => $shopProduct->type,
  88. 'status' => 'paid',
  89. 'amount' => $shopProduct->quantity,
  90. 'price' => $shopProduct->price - ($shopProduct->price*PartnerDiscount::getDiscount()/100),
  91. 'tax_value' => $shopProduct->getTaxValue(),
  92. 'tax_percent' => $shopProduct->getTaxPercent(),
  93. 'total_price' => $shopProduct->getTotalPrice(),
  94. 'currency_code' => $shopProduct->currency_code,
  95. 'shop_item_product_id' => $shopProduct->id,
  96. ]);
  97. event(new UserUpdateCreditsEvent($user));
  98. //not sending an invoice
  99. //redirect back to home
  100. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  101. }
  102. /**
  103. * @param Request $request
  104. * @param ShopProduct $shopProduct
  105. * @return RedirectResponse
  106. */
  107. public function PaypalPay(Request $request, ShopProduct $shopProduct)
  108. {
  109. if(!$this->checkAmount($shopProduct->getTotalPrice(), strtoupper($shopProduct->currency_code), "paypal")) 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.'));
  110. $request = new OrdersCreateRequest();
  111. $request->prefer('return=representation');
  112. $request->body = [
  113. 'intent' => 'CAPTURE',
  114. 'purchase_units' => [
  115. [
  116. 'reference_id' => uniqid(),
  117. 'description' => $shopProduct->display.(PartnerDiscount::getDiscount() ? (' ('.__('Discount').' '.PartnerDiscount::getDiscount().'%)') : ''),
  118. 'amount' => [
  119. 'value' => $shopProduct->getTotalPrice(),
  120. 'currency_code' => strtoupper($shopProduct->currency_code),
  121. 'breakdown' => [
  122. 'item_total' => [
  123. 'currency_code' => strtoupper($shopProduct->currency_code),
  124. 'value' => $shopProduct->getPriceAfterDiscount(),
  125. ],
  126. 'tax_total' => [
  127. 'currency_code' => strtoupper($shopProduct->currency_code),
  128. 'value' => $shopProduct->getTaxValue(),
  129. ],
  130. ],
  131. ],
  132. ],
  133. ],
  134. 'application_context' => [
  135. 'cancel_url' => route('payment.Cancel'),
  136. 'return_url' => route('payment.PaypalSuccess', ['product' => $shopProduct->id]),
  137. 'brand_name' => config('app.name', 'Laravel'),
  138. 'shipping_preference' => 'NO_SHIPPING',
  139. ],
  140. ];
  141. try {
  142. // Call API with your client and get a response for your call
  143. $response = $this->getPayPalClient()->execute($request);
  144. return redirect()->away($response->result->links[1]->href);
  145. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  146. } catch (HttpException $ex) {
  147. echo $ex->statusCode;
  148. dd(json_decode($ex->getMessage()));
  149. }
  150. }
  151. /**
  152. * @return PayPalHttpClient
  153. */
  154. protected function getPayPalClient()
  155. {
  156. $environment = env('APP_ENV') == 'local'
  157. ? new SandboxEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret())
  158. : new ProductionEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret());
  159. return new PayPalHttpClient($environment);
  160. }
  161. /**
  162. * @return string
  163. */
  164. protected function getPaypalClientId()
  165. {
  166. return env('APP_ENV') == 'local' ? config('SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID') : config('SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID');
  167. }
  168. /**
  169. * @return string
  170. */
  171. protected function getPaypalClientSecret()
  172. {
  173. return env('APP_ENV') == 'local' ? config('SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET') : config('SETTINGS::PAYMENTS:PAYPAL:SECRET');
  174. }
  175. /**
  176. * @param Request $laravelRequest
  177. */
  178. public function PaypalSuccess(Request $laravelRequest)
  179. {
  180. /** @var ShopProduct $shopProduct */
  181. $shopProduct = ShopProduct::findOrFail($laravelRequest->input('product'));
  182. /** @var User $user */
  183. $user = Auth::user();
  184. $request = new OrdersCaptureRequest($laravelRequest->input('token'));
  185. $request->prefer('return=representation');
  186. try {
  187. // Call API with your client and get a response for your call
  188. $response = $this->getPayPalClient()->execute($request);
  189. if ($response->statusCode == 201 || $response->statusCode == 200) {
  190. //update server limit
  191. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  192. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  193. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  194. }
  195. }
  196. //update User with bought item
  197. if ($shopProduct->type == 'Credits') {
  198. $user->increment('credits', $shopProduct->quantity);
  199. } elseif ($shopProduct->type == 'Server slots') {
  200. $user->increment('server_limit', $shopProduct->quantity);
  201. }
  202. //give referral commission always
  203. if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits' && config('SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION') == 'true') {
  204. if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) {
  205. $ref_user = User::findOrFail($ref_user->referral_id);
  206. $increment = number_format($shopProduct->quantity * (PartnerDiscount::getCommission($ref_user->id)) / 100, 0, '', '');
  207. $ref_user->increment('credits', $increment);
  208. //LOGS REFERRALS IN THE ACTIVITY LOG
  209. activity()
  210. ->performedOn($user)
  211. ->causedBy($ref_user)
  212. ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  213. }
  214. }
  215. //update role give Referral-reward
  216. if ($user->role == 'member') {
  217. $user->update(['role' => 'client']);
  218. //give referral commission only on first purchase
  219. if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits' && config('SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION') == 'false') {
  220. if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) {
  221. $ref_user = User::findOrFail($ref_user->referral_id);
  222. $increment = number_format($shopProduct->quantity * (PartnerDiscount::getCommission($ref_user->id)) / 100, 0, '', '');
  223. $ref_user->increment('credits', $increment);
  224. //LOGS REFERRALS IN THE ACTIVITY LOG
  225. activity()
  226. ->performedOn($user)
  227. ->causedBy($ref_user)
  228. ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  229. }
  230. }
  231. }
  232. //store payment
  233. $payment = Payment::create([
  234. 'user_id' => $user->id,
  235. 'payment_id' => $response->result->id,
  236. 'payment_method' => 'paypal',
  237. 'type' => $shopProduct->type,
  238. 'status' => 'paid',
  239. 'amount' => $shopProduct->quantity,
  240. 'price' => $shopProduct->price - ($shopProduct->price * PartnerDiscount::getDiscount() / 100),
  241. 'tax_value' => $shopProduct->getTaxValue(),
  242. 'tax_percent' => $shopProduct->getTaxPercent(),
  243. 'total_price' => $shopProduct->getTotalPrice(),
  244. 'currency_code' => $shopProduct->currency_code,
  245. 'shop_item_product_id' => $shopProduct->id,
  246. ]);
  247. event(new UserUpdateCreditsEvent($user));
  248. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  249. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  250. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  251. }
  252. //redirect back to home
  253. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  254. }
  255. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  256. if (env('APP_ENV') == 'local') {
  257. dd($response);
  258. } else {
  259. abort(500);
  260. }
  261. } catch (HttpException $ex) {
  262. if (env('APP_ENV') == 'local') {
  263. echo $ex->statusCode;
  264. dd($ex->getMessage());
  265. } else {
  266. abort(422);
  267. }
  268. }
  269. }
  270. /**
  271. * @param Request $request
  272. */
  273. public function Cancel(Request $request)
  274. {
  275. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  276. }
  277. /**
  278. * @param Request $request
  279. * @param ShopProduct $shopProduct
  280. * @return RedirectResponse
  281. */
  282. public function StripePay(Request $request, ShopProduct $shopProduct)
  283. {
  284. 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.'));
  285. $stripeClient = $this->getStripeClient();
  286. $request = $stripeClient->checkout->sessions->create([
  287. 'line_items' => [
  288. [
  289. 'price_data' => [
  290. 'currency' => $shopProduct->currency_code,
  291. 'product_data' => [
  292. 'name' => $shopProduct->display.(PartnerDiscount::getDiscount() ? (' ('.__('Discount').' '.PartnerDiscount::getDiscount().'%)') : ''),
  293. 'description' => $shopProduct->description,
  294. ],
  295. 'unit_amount_decimal' => round($shopProduct->getPriceAfterDiscount() * 100, 2),
  296. ],
  297. 'quantity' => 1,
  298. ],
  299. [
  300. 'price_data' => [
  301. 'currency' => $shopProduct->currency_code,
  302. 'product_data' => [
  303. 'name' => __('Tax'),
  304. 'description' => $shopProduct->getTaxPercent().'%',
  305. ],
  306. 'unit_amount_decimal' => round($shopProduct->getTaxValue(), 2) * 100,
  307. ],
  308. 'quantity' => 1,
  309. ],
  310. ],
  311. 'mode' => 'payment',
  312. 'payment_method_types' => str_getcsv(config('SETTINGS::PAYMENTS:STRIPE:METHODS')),
  313. 'success_url' => route('payment.StripeSuccess', ['product' => $shopProduct->id]).'&session_id={CHECKOUT_SESSION_ID}',
  314. 'cancel_url' => route('payment.Cancel'),
  315. ]);
  316. return redirect($request->url, 303);
  317. }
  318. /**
  319. * @param Request $request
  320. */
  321. public function StripeSuccess(Request $request)
  322. {
  323. /** @var ShopProduct $shopProduct */
  324. $shopProduct = ShopProduct::findOrFail($request->input('product'));
  325. /** @var User $user */
  326. $user = Auth::user();
  327. $stripeClient = $this->getStripeClient();
  328. try {
  329. //get stripe data
  330. $paymentSession = $stripeClient->checkout->sessions->retrieve($request->input('session_id'));
  331. $paymentIntent = $stripeClient->paymentIntents->retrieve($paymentSession->payment_intent);
  332. //get DB entry of this payment ID if existing
  333. $paymentDbEntry = Payment::where('payment_id', $paymentSession->payment_intent)->count();
  334. // check if payment is 100% completed and payment does not exist in db already
  335. if ($paymentSession->status == 'complete' && $paymentIntent->status == 'succeeded' && $paymentDbEntry == 0) {
  336. //update server limit
  337. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  338. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  339. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  340. }
  341. }
  342. //update User with bought item
  343. if ($shopProduct->type == 'Credits') {
  344. $user->increment('credits', $shopProduct->quantity);
  345. } elseif ($shopProduct->type == 'Server slots') {
  346. $user->increment('server_limit', $shopProduct->quantity);
  347. }
  348. //update role give Referral-reward
  349. if ($user->role == 'member') {
  350. $user->update(['role' => 'client']);
  351. if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits') {
  352. if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) {
  353. $ref_user = User::findOrFail($ref_user->referral_id);
  354. $increment = number_format($shopProduct->quantity / 100 * config('SETTINGS::REFERRAL:PERCENTAGE'), 0, '', '');
  355. $ref_user->increment('credits', $increment);
  356. //LOGS REFERRALS IN THE ACTIVITY LOG
  357. activity()
  358. ->performedOn($user)
  359. ->causedBy($ref_user)
  360. ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  361. }
  362. }
  363. }
  364. //store paid payment
  365. $payment = Payment::create([
  366. 'user_id' => $user->id,
  367. 'payment_id' => $paymentSession->payment_intent,
  368. 'payment_method' => 'stripe',
  369. 'type' => $shopProduct->type,
  370. 'status' => 'paid',
  371. 'amount' => $shopProduct->quantity,
  372. 'price' => $shopProduct->price - ($shopProduct->price * PartnerDiscount::getDiscount() / 100),
  373. 'tax_value' => $shopProduct->getTaxValue(),
  374. 'total_price' => $shopProduct->getTotalPrice(),
  375. 'tax_percent' => $shopProduct->getTaxPercent(),
  376. 'currency_code' => $shopProduct->currency_code,
  377. 'shop_item_product_id' => $shopProduct->id,
  378. ]);
  379. //payment notification
  380. $user->notify(new ConfirmPaymentNotification($payment));
  381. event(new UserUpdateCreditsEvent($user));
  382. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  383. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  384. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  385. }
  386. //redirect back to home
  387. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  388. } else {
  389. if ($paymentIntent->status == 'processing') {
  390. //store processing payment
  391. $payment = Payment::create([
  392. 'user_id' => $user->id,
  393. 'payment_id' => $paymentSession->payment_intent,
  394. 'payment_method' => 'stripe',
  395. 'type' => $shopProduct->type,
  396. 'status' => 'processing',
  397. 'amount' => $shopProduct->quantity,
  398. 'price' => $shopProduct->price,
  399. 'tax_value' => $shopProduct->getTaxValue(),
  400. 'total_price' => $shopProduct->getTotalPrice(),
  401. 'tax_percent' => $shopProduct->getTaxPercent(),
  402. 'currency_code' => $shopProduct->currency_code,
  403. 'shop_item_product_id' => $shopProduct->id,
  404. ]);
  405. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  406. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  407. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  408. }
  409. //redirect back to home
  410. return redirect()->route('home')->with('success', __('Your payment is being processed!'));
  411. }
  412. if ($paymentDbEntry == 0 && $paymentIntent->status != 'processing') {
  413. $stripeClient->paymentIntents->cancel($paymentIntent->id);
  414. //redirect back to home
  415. return redirect()->route('home')->with('success', __('Your payment has been canceled!'));
  416. } else {
  417. abort(402);
  418. }
  419. }
  420. } catch (HttpException $ex) {
  421. if (env('APP_ENV') == 'local') {
  422. echo $ex->statusCode;
  423. dd($ex->getMessage());
  424. } else {
  425. abort(422);
  426. }
  427. }
  428. }
  429. /**
  430. * @param Request $request
  431. */
  432. protected function handleStripePaymentSuccessHook($paymentIntent)
  433. {
  434. try {
  435. // Get payment db entry
  436. $payment = Payment::where('payment_id', $paymentIntent->id)->first();
  437. $user = User::where('id', $payment->user_id)->first();
  438. if ($paymentIntent->status == 'succeeded' && $payment->status == 'processing') {
  439. //update server limit
  440. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  441. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  442. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  443. }
  444. }
  445. //update User with bought item
  446. if ($shopProduct->type == 'Credits') {
  447. $user->increment('credits', $shopProduct->quantity);
  448. } elseif ($shopProduct->type == 'Server slots') {
  449. $user->increment('server_limit', $shopProduct->quantity);
  450. }
  451. //update role give Referral-reward
  452. if ($user->role == 'member') {
  453. $user->update(['role' => 'client']);
  454. if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits') {
  455. if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) {
  456. $ref_user = User::findOrFail($ref_user->referral_id);
  457. $increment = number_format($shopProduct->quantity / 100 * config('SETTINGS::REFERRAL:PERCENTAGE'), 0, '', '');
  458. $ref_user->increment('credits', $increment);
  459. //LOGS REFERRALS IN THE ACTIVITY LOG
  460. activity()
  461. ->performedOn($user)
  462. ->causedBy($ref_user)
  463. ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  464. }
  465. }
  466. }
  467. //update payment db entry status
  468. $payment->update(['status' => 'paid']);
  469. //payment notification
  470. $user->notify(new ConfirmPaymentNotification($payment));
  471. event(new UserUpdateCreditsEvent($user));
  472. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  473. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  474. $this->createInvoice($user, $payment, 'paid', strtoupper($paymentIntent->currency));
  475. }
  476. }
  477. } catch (HttpException $ex) {
  478. abort(422);
  479. }
  480. }
  481. /**
  482. * @param Request $request
  483. */
  484. public function StripeWebhooks(Request $request)
  485. {
  486. \Stripe\Stripe::setApiKey($this->getStripeSecret());
  487. try {
  488. $payload = @file_get_contents('php://input');
  489. $sig_header = $request->header('Stripe-Signature');
  490. $event = null;
  491. $event = \Stripe\Webhook::constructEvent(
  492. $payload,
  493. $sig_header,
  494. $this->getStripeEndpointSecret()
  495. );
  496. } catch (\UnexpectedValueException $e) {
  497. // Invalid payload
  498. abort(400);
  499. } catch (\Stripe\Exception\SignatureVerificationException $e) {
  500. // Invalid signature
  501. abort(400);
  502. }
  503. // Handle the event
  504. switch ($event->type) {
  505. case 'payment_intent.succeeded':
  506. $paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
  507. $this->handleStripePaymentSuccessHook($paymentIntent);
  508. break;
  509. default:
  510. echo 'Received unknown event type '.$event->type;
  511. }
  512. }
  513. /**
  514. * @return \Stripe\StripeClient
  515. */
  516. protected function getStripeClient()
  517. {
  518. return new \Stripe\StripeClient($this->getStripeSecret());
  519. }
  520. /**
  521. * @return string
  522. */
  523. protected function getStripeSecret()
  524. {
  525. return env('APP_ENV') == 'local'
  526. ? config('SETTINGS::PAYMENTS:STRIPE:TEST_SECRET')
  527. : config('SETTINGS::PAYMENTS:STRIPE:SECRET');
  528. }
  529. /**
  530. * @return string
  531. */
  532. protected function getStripeEndpointSecret()
  533. {
  534. return env('APP_ENV') == 'local'
  535. ? config('SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET')
  536. : config('SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET');
  537. }
  538. protected function createInvoice($user, $payment, $paymentStatus, $currencyCode)
  539. {
  540. $shopProduct = ShopProduct::where('id', $payment->shop_item_product_id)->first();
  541. //create invoice
  542. $lastInvoiceID = \App\Models\Invoice::where('invoice_name', 'like', '%'.now()->format('mY').'%')->count('id');
  543. $newInvoiceID = $lastInvoiceID + 1;
  544. $logoPath = storage_path('app/public/logo.png');
  545. $seller = new Party([
  546. 'name' => config('SETTINGS::INVOICE:COMPANY_NAME'),
  547. 'phone' => config('SETTINGS::INVOICE:COMPANY_PHONE'),
  548. 'address' => config('SETTINGS::INVOICE:COMPANY_ADDRESS'),
  549. 'vat' => config('SETTINGS::INVOICE:COMPANY_VAT'),
  550. 'custom_fields' => [
  551. 'E-Mail' => config('SETTINGS::INVOICE:COMPANY_MAIL'),
  552. 'Web' => config('SETTINGS::INVOICE:COMPANY_WEBSITE'),
  553. ],
  554. ]);
  555. $customer = new Buyer([
  556. 'name' => $user->name,
  557. 'custom_fields' => [
  558. 'E-Mail' => $user->email,
  559. 'Client ID' => $user->id,
  560. ],
  561. ]);
  562. $item = (new InvoiceItem())
  563. ->title($shopProduct->description)
  564. ->pricePerUnit($shopProduct->price);
  565. $notes = [
  566. __('Payment method').': '.$payment->payment_method,
  567. ];
  568. $notes = implode('<br>', $notes);
  569. $invoice = Invoice::make()
  570. ->template('controlpanel')
  571. ->name(__('Invoice'))
  572. ->buyer($customer)
  573. ->seller($seller)
  574. ->discountByPercent(PartnerDiscount::getDiscount())
  575. ->taxRate(floatval($shopProduct->getTaxPercent()))
  576. ->shipping(0)
  577. ->addItem($item)
  578. ->status(__($paymentStatus))
  579. ->series(now()->format('mY'))
  580. ->delimiter('-')
  581. ->sequence($newInvoiceID)
  582. ->serialNumberFormat(config('SETTINGS::INVOICE:PREFIX').'{DELIMITER}{SERIES}{SEQUENCE}')
  583. ->currencyCode($currencyCode)
  584. ->currencySymbol(Currencies::getSymbol($currencyCode))
  585. ->notes($notes);
  586. if (file_exists($logoPath)) {
  587. $invoice->logo($logoPath);
  588. }
  589. //Save the invoice in "storage\app\invoice\USER_ID\YEAR"
  590. $invoice->filename = $invoice->getSerialNumber().'.pdf';
  591. $invoice->render();
  592. Storage::disk('local')->put('invoice/'.$user->id.'/'.now()->format('Y').'/'.$invoice->filename, $invoice->output);
  593. \App\Models\Invoice::create([
  594. 'invoice_user' => $user->id,
  595. 'invoice_name' => $invoice->getSerialNumber(),
  596. 'payment_id' => $payment->payment_id,
  597. ]);
  598. //Send Invoice per Mail
  599. $user->notify(new InvoiceNotification($invoice, $user, $payment));
  600. }
  601. public function checkAmount($amount, $currencyCode, $payment_method)
  602. {
  603. $minimums = [
  604. "USD" => [
  605. "paypal" => 0,
  606. "stripe" => 0.5
  607. ],
  608. "AED" => [
  609. "paypal" => 0,
  610. "stripe" => 2
  611. ],
  612. "AUD" => [
  613. "paypal" => 0,
  614. "stripe" => 0.5
  615. ],
  616. "BGN" => [
  617. "paypal" => 0,
  618. "stripe" => 1
  619. ],
  620. "BRL" => [
  621. "paypal" => 0,
  622. "stripe" => 0.5
  623. ],
  624. "CAD" => [
  625. "paypal" => 0,
  626. "stripe" => 0.5
  627. ],
  628. "CHF" => [
  629. "paypal" => 0,
  630. "stripe" => 0.5
  631. ],
  632. "CZK" => [
  633. "paypal" => 0,
  634. "stripe" => 15
  635. ],
  636. "DKK" => [
  637. "paypal" => 0,
  638. "stripe" => 2.5
  639. ],
  640. "EUR" => [
  641. "paypal" => 0,
  642. "stripe" => 0.5
  643. ],
  644. "GBP" => [
  645. "paypal" => 0,
  646. "stripe" => 0.3
  647. ],
  648. "HKD" => [
  649. "paypal" => 0,
  650. "stripe" => 4
  651. ],
  652. "HRK" => [
  653. "paypal" => 0,
  654. "stripe" => 0.5
  655. ],
  656. "HUF" => [
  657. "paypal" => 0,
  658. "stripe" => 175
  659. ],
  660. "INR" => [
  661. "paypal" => 0,
  662. "stripe" => 0.5
  663. ],
  664. "JPY" => [
  665. "paypal" => 0,
  666. "stripe" => 0.5
  667. ],
  668. "MXN" => [
  669. "paypal" => 0,
  670. "stripe" => 10
  671. ],
  672. "MYR" => [
  673. "paypal" => 0,
  674. "stripe" => 2
  675. ],
  676. "NOK" => [
  677. "paypal" => 0,
  678. "stripe" => 3
  679. ],
  680. "NZD" => [
  681. "paypal" => 0,
  682. "stripe" => 0.5
  683. ],
  684. "PLN" => [
  685. "paypal" => 0,
  686. "stripe" => 2
  687. ],
  688. "RON" => [
  689. "paypal" => 0,
  690. "stripe" => 2
  691. ],
  692. "SEK" => [
  693. "paypal" => 0,
  694. "stripe" => 3
  695. ],
  696. "SGD" => [
  697. "paypal" => 0,
  698. "stripe" => 0.5
  699. ],
  700. "THB" => [
  701. "paypal" => 0,
  702. "stripe" => 10
  703. ]
  704. ];
  705. return $amount >= $minimums[$currencyCode][$payment_method];
  706. }
  707. /**
  708. * @return JsonResponse|mixed
  709. *
  710. * @throws Exception
  711. */
  712. public function dataTable()
  713. {
  714. $query = Payment::with('user');
  715. return datatables($query)
  716. ->addColumn('user', function (Payment $payment) {
  717. return
  718. ($payment->user)?'<a href="'.route('admin.users.show', $payment->user->id).'">'.$payment->user->name.'</a>':__('Unknown user');
  719. })
  720. ->editColumn('price', function (Payment $payment) {
  721. return $payment->formatToCurrency($payment->price);
  722. })
  723. ->editColumn('tax_value', function (Payment $payment) {
  724. return $payment->formatToCurrency($payment->tax_value);
  725. })
  726. ->editColumn('tax_percent', function (Payment $payment) {
  727. return $payment->tax_percent.' %';
  728. })
  729. ->editColumn('total_price', function (Payment $payment) {
  730. return $payment->formatToCurrency($payment->total_price);
  731. })
  732. ->editColumn('created_at', function (Payment $payment) {
  733. return ['display' => $payment->created_at ? $payment->created_at->diffForHumans() : '',
  734. 'raw' => $payment->created_at ? strtotime($payment->created_at) : ''];
  735. })
  736. ->addColumn('actions', function (Payment $payment) {
  737. 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>';
  738. })
  739. ->rawColumns(['actions', 'user'])
  740. ->make(true);
  741. }
  742. }