PaymentController.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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\Settings;
  8. use App\Models\ShopProduct;
  9. use App\Models\User;
  10. use App\Notifications\ConfirmPaymentNotification;
  11. use App\Notifications\InvoiceNotification;
  12. use Exception;
  13. use Illuminate\Contracts\Foundation\Application;
  14. use Illuminate\Contracts\View\Factory;
  15. use Illuminate\Contracts\View\View;
  16. use Illuminate\Http\JsonResponse;
  17. use Illuminate\Http\RedirectResponse;
  18. use Illuminate\Http\Request;
  19. use Illuminate\Support\Facades\Auth;
  20. use Illuminate\Support\Facades\DB;
  21. use Illuminate\Support\Facades\Log;
  22. use Illuminate\Support\Facades\Storage;
  23. use LaravelDaily\Invoices\Classes\Buyer;
  24. use LaravelDaily\Invoices\Classes\InvoiceItem;
  25. use LaravelDaily\Invoices\Classes\Party;
  26. use LaravelDaily\Invoices\Invoice;
  27. use PayPalCheckoutSdk\Core\PayPalHttpClient;
  28. use PayPalCheckoutSdk\Core\ProductionEnvironment;
  29. use PayPalCheckoutSdk\Core\SandboxEnvironment;
  30. use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
  31. use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
  32. use PayPalHttp\HttpException;
  33. use Stripe\Stripe;
  34. use Symfony\Component\Intl\Currencies;
  35. class PaymentController extends Controller
  36. {
  37. /**
  38. * @return Application|Factory|View
  39. */
  40. public function index()
  41. {
  42. return view('admin.payments.index')->with([
  43. 'payments' => Payment::paginate(15),
  44. ]);
  45. }
  46. /**
  47. * @param Request $request
  48. * @param ShopProduct $shopProduct
  49. * @return Application|Factory|View
  50. */
  51. public function checkOut(Request $request, ShopProduct $shopProduct)
  52. {
  53. return view('store.checkout')->with([
  54. 'product' => $shopProduct,
  55. 'discountpercent' => PartnerDiscount::getDiscount(),
  56. 'discountvalue' => PartnerDiscount::getDiscount() * $shopProduct->price / 100,
  57. 'discountedprice' => $shopProduct->getPriceAfterDiscount(),
  58. 'taxvalue' => $shopProduct->getTaxValue(),
  59. 'taxpercent' => $shopProduct->getTaxPercent(),
  60. 'total' => $shopProduct->getTotalPrice(),
  61. ]);
  62. }
  63. /**
  64. * @param Request $request
  65. * @param ShopProduct $shopProduct
  66. * @return RedirectResponse
  67. */
  68. public function PaypalPay(Request $request, ShopProduct $shopProduct)
  69. {
  70. $request = new OrdersCreateRequest();
  71. $request->prefer('return=representation');
  72. $request->body = [
  73. 'intent' => 'CAPTURE',
  74. 'purchase_units' => [
  75. [
  76. 'reference_id' => uniqid(),
  77. 'description' => $shopProduct->display.(PartnerDiscount::getDiscount() ? (' ('.__('Discount').' '.PartnerDiscount::getDiscount().'%)') : ''),
  78. 'amount' => [
  79. 'value' => $shopProduct->getTotalPrice(),
  80. 'currency_code' => strtoupper($shopProduct->currency_code),
  81. 'breakdown' => [
  82. 'item_total' => [
  83. 'currency_code' => strtoupper($shopProduct->currency_code),
  84. 'value' => $shopProduct->getPriceAfterDiscount(),
  85. ],
  86. 'tax_total' => [
  87. 'currency_code' => strtoupper($shopProduct->currency_code),
  88. 'value' => $shopProduct->getTaxValue(),
  89. ],
  90. ],
  91. ],
  92. ],
  93. ],
  94. 'application_context' => [
  95. 'cancel_url' => route('payment.Cancel'),
  96. 'return_url' => route('payment.PaypalSuccess', ['product' => $shopProduct->id]),
  97. 'brand_name' => config('app.name', 'Laravel'),
  98. 'shipping_preference' => 'NO_SHIPPING',
  99. ],
  100. ];
  101. try {
  102. // Call API with your client and get a response for your call
  103. $response = $this->getPayPalClient()->execute($request);
  104. return redirect()->away($response->result->links[1]->href);
  105. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  106. } catch (HttpException $ex) {
  107. echo $ex->statusCode;
  108. dd(json_decode($ex->getMessage()));
  109. }
  110. }
  111. /**
  112. * @return PayPalHttpClient
  113. */
  114. protected function getPayPalClient()
  115. {
  116. $environment = env('APP_ENV') == 'local'
  117. ? new SandboxEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret())
  118. : new ProductionEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret());
  119. return new PayPalHttpClient($environment);
  120. }
  121. /**
  122. * @return string
  123. */
  124. protected function getPaypalClientId()
  125. {
  126. return env('APP_ENV') == 'local' ? config('SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID') : config('SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID');
  127. }
  128. /**
  129. * @return string
  130. */
  131. protected function getPaypalClientSecret()
  132. {
  133. return env('APP_ENV') == 'local' ? config('SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET') : config('SETTINGS::PAYMENTS:PAYPAL:SECRET');
  134. }
  135. /**
  136. * @param Request $laravelRequest
  137. */
  138. public function PaypalSuccess(Request $laravelRequest)
  139. {
  140. /** @var ShopProduct $shopProduct */
  141. $shopProduct = ShopProduct::findOrFail($laravelRequest->input('product'));
  142. /** @var User $user */
  143. $user = Auth::user();
  144. $request = new OrdersCaptureRequest($laravelRequest->input('token'));
  145. $request->prefer('return=representation');
  146. try {
  147. // Call API with your client and get a response for your call
  148. $response = $this->getPayPalClient()->execute($request);
  149. if ($response->statusCode == 201 || $response->statusCode == 200) {
  150. //update server limit
  151. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  152. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  153. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  154. }
  155. }
  156. //update User with bought item
  157. if ($shopProduct->type == 'Credits') {
  158. $user->increment('credits', $shopProduct->quantity);
  159. } elseif ($shopProduct->type == 'Server slots') {
  160. $user->increment('server_limit', $shopProduct->quantity);
  161. }
  162. //give referral commission always
  163. if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits' && config('SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION') == 'true') {
  164. if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) {
  165. $ref_user = User::findOrFail($ref_user->referral_id);
  166. $increment = number_format($shopProduct->quantity * (PartnerDiscount::getCommission($ref_user->id)) / 100, 0, '', '');
  167. $ref_user->increment('credits', $increment);
  168. //LOGS REFERRALS IN THE ACTIVITY LOG
  169. activity()
  170. ->performedOn($user)
  171. ->causedBy($ref_user)
  172. ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  173. }
  174. }
  175. //update role give Referral-reward
  176. if ($user->role == 'member') {
  177. $user->update(['role' => 'client']);
  178. //give referral commission only on first purchase
  179. if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits' && config('SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION') == 'false') {
  180. if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) {
  181. $ref_user = User::findOrFail($ref_user->referral_id);
  182. $increment = number_format($shopProduct->quantity * (PartnerDiscount::getCommission($ref_user->id)) / 100, 0, '', '');
  183. $ref_user->increment('credits', $increment);
  184. //LOGS REFERRALS IN THE ACTIVITY LOG
  185. activity()
  186. ->performedOn($user)
  187. ->causedBy($ref_user)
  188. ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  189. }
  190. }
  191. }
  192. //store payment
  193. $payment = Payment::create([
  194. 'user_id' => $user->id,
  195. 'payment_id' => $response->result->id,
  196. 'payment_method' => 'paypal',
  197. 'type' => $shopProduct->type,
  198. 'status' => 'paid',
  199. 'amount' => $shopProduct->quantity,
  200. 'price' => $shopProduct->price - ($shopProduct->price * PartnerDiscount::getDiscount() / 100),
  201. 'tax_value' => $shopProduct->getTaxValue(),
  202. 'tax_percent' => $shopProduct->getTaxPercent(),
  203. 'total_price' => $shopProduct->getTotalPrice(),
  204. 'currency_code' => $shopProduct->currency_code,
  205. 'shop_item_product_id' => $shopProduct->id,
  206. ]);
  207. event(new UserUpdateCreditsEvent($user));
  208. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  209. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  210. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  211. }
  212. //redirect back to home
  213. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  214. }
  215. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  216. if (env('APP_ENV') == 'local') {
  217. dd($response);
  218. } else {
  219. abort(500);
  220. }
  221. } catch (HttpException $ex) {
  222. if (env('APP_ENV') == 'local') {
  223. echo $ex->statusCode;
  224. dd($ex->getMessage());
  225. } else {
  226. abort(422);
  227. }
  228. }
  229. }
  230. /**
  231. * @param Request $request
  232. */
  233. public function Cancel(Request $request)
  234. {
  235. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  236. }
  237. /**
  238. * @param Request $request
  239. * @param ShopProduct $shopProduct
  240. * @return RedirectResponse
  241. */
  242. public function StripePay(Request $request, ShopProduct $shopProduct)
  243. {
  244. $stripeClient = $this->getStripeClient();
  245. $request = $stripeClient->checkout->sessions->create([
  246. 'line_items' => [
  247. [
  248. 'price_data' => [
  249. 'currency' => $shopProduct->currency_code,
  250. 'product_data' => [
  251. 'name' => $shopProduct->display.(PartnerDiscount::getDiscount() ? (' ('.__('Discount').' '.PartnerDiscount::getDiscount().'%)') : ''),
  252. 'description' => $shopProduct->description,
  253. ],
  254. 'unit_amount_decimal' => round($shopProduct->getPriceAfterDiscount() * 100, 2),
  255. ],
  256. 'quantity' => 1,
  257. ],
  258. [
  259. 'price_data' => [
  260. 'currency' => $shopProduct->currency_code,
  261. 'product_data' => [
  262. 'name' => __('Tax'),
  263. 'description' => $shopProduct->getTaxPercent().'%',
  264. ],
  265. 'unit_amount_decimal' => round($shopProduct->getTaxValue(), 2) * 100,
  266. ],
  267. 'quantity' => 1,
  268. ],
  269. ],
  270. 'mode' => 'payment',
  271. 'payment_method_types' => str_getcsv(config('SETTINGS::PAYMENTS:STRIPE:METHODS')),
  272. 'success_url' => route('payment.StripeSuccess', ['product' => $shopProduct->id]).'&session_id={CHECKOUT_SESSION_ID}',
  273. 'cancel_url' => route('payment.Cancel'),
  274. ]);
  275. return redirect($request->url, 303);
  276. }
  277. /**
  278. * @param Request $request
  279. */
  280. public function StripeSuccess(Request $request)
  281. {
  282. /** @var ShopProduct $shopProduct */
  283. $shopProduct = ShopProduct::findOrFail($request->input('product'));
  284. /** @var User $user */
  285. $user = Auth::user();
  286. $stripeClient = $this->getStripeClient();
  287. try {
  288. //get stripe data
  289. $paymentSession = $stripeClient->checkout->sessions->retrieve($request->input('session_id'));
  290. $paymentIntent = $stripeClient->paymentIntents->retrieve($paymentSession->payment_intent);
  291. //get DB entry of this payment ID if existing
  292. $paymentDbEntry = Payment::where('payment_id', $paymentSession->payment_intent)->count();
  293. // check if payment is 100% completed and payment does not exist in db already
  294. if ($paymentSession->status == 'complete' && $paymentIntent->status == 'succeeded' && $paymentDbEntry == 0) {
  295. //update server limit
  296. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  297. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  298. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  299. }
  300. }
  301. //update User with bought item
  302. if ($shopProduct->type == 'Credits') {
  303. $user->increment('credits', $shopProduct->quantity);
  304. } elseif ($shopProduct->type == 'Server slots') {
  305. $user->increment('server_limit', $shopProduct->quantity);
  306. }
  307. //update role give Referral-reward
  308. if ($user->role == 'member') {
  309. $user->update(['role' => 'client']);
  310. if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits') {
  311. if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) {
  312. $ref_user = User::findOrFail($ref_user->referral_id);
  313. $increment = number_format($shopProduct->quantity / 100 * config('SETTINGS::REFERRAL:PERCENTAGE'), 0, '', '');
  314. $ref_user->increment('credits', $increment);
  315. //LOGS REFERRALS IN THE ACTIVITY LOG
  316. activity()
  317. ->performedOn($user)
  318. ->causedBy($ref_user)
  319. ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  320. }
  321. }
  322. }
  323. //store paid payment
  324. $payment = Payment::create([
  325. 'user_id' => $user->id,
  326. 'payment_id' => $paymentSession->payment_intent,
  327. 'payment_method' => 'stripe',
  328. 'type' => $shopProduct->type,
  329. 'status' => 'paid',
  330. 'amount' => $shopProduct->quantity,
  331. 'price' => $shopProduct->price - ($shopProduct->price * PartnerDiscount::getDiscount() / 100),
  332. 'tax_value' => $shopProduct->getTaxValue(),
  333. 'total_price' => $shopProduct->getTotalPrice(),
  334. 'tax_percent' => $shopProduct->getTaxPercent(),
  335. 'currency_code' => $shopProduct->currency_code,
  336. 'shop_item_product_id' => $shopProduct->id,
  337. ]);
  338. //payment notification
  339. $user->notify(new ConfirmPaymentNotification($payment));
  340. event(new UserUpdateCreditsEvent($user));
  341. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  342. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  343. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  344. }
  345. //redirect back to home
  346. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  347. } else {
  348. if ($paymentIntent->status == 'processing') {
  349. //store processing payment
  350. $payment = Payment::create([
  351. 'user_id' => $user->id,
  352. 'payment_id' => $paymentSession->payment_intent,
  353. 'payment_method' => 'stripe',
  354. 'type' => $shopProduct->type,
  355. 'status' => 'processing',
  356. 'amount' => $shopProduct->quantity,
  357. 'price' => $shopProduct->price,
  358. 'tax_value' => $shopProduct->getTaxValue(),
  359. 'total_price' => $shopProduct->getTotalPrice(),
  360. 'tax_percent' => $shopProduct->getTaxPercent(),
  361. 'currency_code' => $shopProduct->currency_code,
  362. 'shop_item_product_id' => $shopProduct->id,
  363. ]);
  364. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  365. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  366. $this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
  367. }
  368. //redirect back to home
  369. return redirect()->route('home')->with('success', __('Your payment is being processed!'));
  370. }
  371. if ($paymentDbEntry == 0 && $paymentIntent->status != 'processing') {
  372. $stripeClient->paymentIntents->cancel($paymentIntent->id);
  373. //redirect back to home
  374. return redirect()->route('home')->with('success', __('Your payment has been canceled!'));
  375. } else {
  376. abort(402);
  377. }
  378. }
  379. } catch (HttpException $ex) {
  380. if (env('APP_ENV') == 'local') {
  381. echo $ex->statusCode;
  382. dd($ex->getMessage());
  383. } else {
  384. abort(422);
  385. }
  386. }
  387. }
  388. /**
  389. * @param Request $request
  390. */
  391. protected function handleStripePaymentSuccessHook($paymentIntent)
  392. {
  393. try {
  394. // Get payment db entry
  395. $payment = Payment::where('payment_id', $paymentIntent->id)->first();
  396. $user = User::where('id', $payment->user_id)->first();
  397. if ($paymentIntent->status == 'succeeded' && $payment->status == 'processing') {
  398. //update server limit
  399. if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  400. if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  401. $user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  402. }
  403. }
  404. //update User with bought item
  405. if ($shopProduct->type == 'Credits') {
  406. $user->increment('credits', $shopProduct->quantity);
  407. } elseif ($shopProduct->type == 'Server slots') {
  408. $user->increment('server_limit', $shopProduct->quantity);
  409. }
  410. //update role give Referral-reward
  411. if ($user->role == 'member') {
  412. $user->update(['role' => 'client']);
  413. if ((config('SETTINGS::REFERRAL:MODE') == 'commission' || config('SETTINGS::REFERRAL:MODE') == 'both') && $shopProduct->type == 'Credits') {
  414. if ($ref_user = DB::table('user_referrals')->where('registered_user_id', '=', $user->id)->first()) {
  415. $ref_user = User::findOrFail($ref_user->referral_id);
  416. $increment = number_format($shopProduct->quantity / 100 * config('SETTINGS::REFERRAL:PERCENTAGE'), 0, '', '');
  417. $ref_user->increment('credits', $increment);
  418. //LOGS REFERRALS IN THE ACTIVITY LOG
  419. activity()
  420. ->performedOn($user)
  421. ->causedBy($ref_user)
  422. ->log('gained '.$increment.' '.config('SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME').' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
  423. }
  424. }
  425. }
  426. //update payment db entry status
  427. $payment->update(['status' => 'paid']);
  428. //payment notification
  429. $user->notify(new ConfirmPaymentNotification($payment));
  430. event(new UserUpdateCreditsEvent($user));
  431. //only create invoice if SETTINGS::INVOICE:ENABLED is true
  432. if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
  433. $this->createInvoice($user, $payment, 'paid', strtoupper($paymentIntent->currency));
  434. }
  435. }
  436. } catch (HttpException $ex) {
  437. abort(422);
  438. }
  439. }
  440. /**
  441. * @param Request $request
  442. */
  443. public function StripeWebhooks(Request $request)
  444. {
  445. \Stripe\Stripe::setApiKey($this->getStripeSecret());
  446. try {
  447. $payload = @file_get_contents('php://input');
  448. $sig_header = $request->header('Stripe-Signature');
  449. $event = null;
  450. $event = \Stripe\Webhook::constructEvent(
  451. $payload,
  452. $sig_header,
  453. $this->getStripeEndpointSecret()
  454. );
  455. } catch (\UnexpectedValueException $e) {
  456. // Invalid payload
  457. abort(400);
  458. } catch (\Stripe\Exception\SignatureVerificationException $e) {
  459. // Invalid signature
  460. abort(400);
  461. }
  462. // Handle the event
  463. switch ($event->type) {
  464. case 'payment_intent.succeeded':
  465. $paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
  466. $this->handleStripePaymentSuccessHook($paymentIntent);
  467. break;
  468. default:
  469. echo 'Received unknown event type '.$event->type;
  470. }
  471. }
  472. /**
  473. * @return \Stripe\StripeClient
  474. */
  475. protected function getStripeClient()
  476. {
  477. return new \Stripe\StripeClient($this->getStripeSecret());
  478. }
  479. /**
  480. * @return string
  481. */
  482. protected function getStripeSecret()
  483. {
  484. return env('APP_ENV') == 'local'
  485. ? config('SETTINGS::PAYMENTS:STRIPE:TEST_SECRET')
  486. : config('SETTINGS::PAYMENTS:STRIPE:SECRET');
  487. }
  488. /**
  489. * @return string
  490. */
  491. protected function getStripeEndpointSecret()
  492. {
  493. return env('APP_ENV') == 'local'
  494. ? config('SETTINGS::PAYMENTS:STRIPE:ENDPOINT_TEST_SECRET')
  495. : config('SETTINGS::PAYMENTS:STRIPE:ENDPOINT_SECRET');
  496. }
  497. protected function createInvoice($user, $payment, $paymentStatus, $currencyCode)
  498. {
  499. $shopProduct = ShopProduct::where('id', $payment->shop_item_product_id)->first();
  500. //create invoice
  501. $lastInvoiceID = \App\Models\Invoice::where('invoice_name', 'like', '%'.now()->format('mY').'%')->count('id');
  502. $newInvoiceID = $lastInvoiceID + 1;
  503. $logoPath = storage_path('app/public/logo.png');
  504. $seller = new Party([
  505. 'name' => config('SETTINGS::INVOICE:COMPANY_NAME'),
  506. 'phone' => config('SETTINGS::INVOICE:COMPANY_PHONE'),
  507. 'address' => config('SETTINGS::INVOICE:COMPANY_ADDRESS'),
  508. 'vat' => config('SETTINGS::INVOICE:COMPANY_VAT'),
  509. 'custom_fields' => [
  510. 'E-Mail' => config('SETTINGS::INVOICE:COMPANY_MAIL'),
  511. 'Web' => config('SETTINGS::INVOICE:COMPANY_WEBSITE'),
  512. ],
  513. ]);
  514. $customer = new Buyer([
  515. 'name' => $user->name,
  516. 'custom_fields' => [
  517. 'E-Mail' => $user->email,
  518. 'Client ID' => $user->id,
  519. ],
  520. ]);
  521. $item = (new InvoiceItem())
  522. ->title($shopProduct->description)
  523. ->pricePerUnit($shopProduct->price);
  524. $notes = [
  525. __('Payment method').': '.$payment->payment_method,
  526. ];
  527. $notes = implode('<br>', $notes);
  528. $invoice = Invoice::make()
  529. ->template('controlpanel')
  530. ->name(__('Invoice'))
  531. ->buyer($customer)
  532. ->seller($seller)
  533. ->discountByPercent(PartnerDiscount::getDiscount())
  534. ->taxRate(floatval($shopProduct->getTaxPercent()))
  535. ->shipping(0)
  536. ->addItem($item)
  537. ->status(__($paymentStatus))
  538. ->series(now()->format('mY'))
  539. ->delimiter('-')
  540. ->sequence($newInvoiceID)
  541. ->serialNumberFormat(config('SETTINGS::INVOICE:PREFIX').'{DELIMITER}{SERIES}{SEQUENCE}')
  542. ->currencyCode($currencyCode)
  543. ->currencySymbol(Currencies::getSymbol($currencyCode))
  544. ->notes($notes);
  545. if (file_exists($logoPath)) {
  546. $invoice->logo($logoPath);
  547. }
  548. //Save the invoice in "storage\app\invoice\USER_ID\YEAR"
  549. $invoice->filename = $invoice->getSerialNumber().'.pdf';
  550. $invoice->render();
  551. Storage::disk('local')->put('invoice/'.$user->id.'/'.now()->format('Y').'/'.$invoice->filename, $invoice->output);
  552. \App\Models\Invoice::create([
  553. 'invoice_user' => $user->id,
  554. 'invoice_name' => $invoice->getSerialNumber(),
  555. 'payment_id' => $payment->payment_id,
  556. ]);
  557. //Send Invoice per Mail
  558. $user->notify(new InvoiceNotification($invoice, $user, $payment));
  559. }
  560. /**
  561. * @return JsonResponse|mixed
  562. *
  563. * @throws Exception
  564. */
  565. public function dataTable()
  566. {
  567. $query = Payment::with('user');
  568. return datatables($query)
  569. ->editColumn('user', function (Payment $payment) {
  570. return
  571. ($payment->user) ? '<a href="'.route('admin.users.show', $payment->user->id).'">'.$payment->user->name.'</a>' : __('Unknown user');
  572. })
  573. ->editColumn('price', function (Payment $payment) {
  574. return $payment->formatToCurrency($payment->price);
  575. })
  576. ->editColumn('tax_value', function (Payment $payment) {
  577. return $payment->formatToCurrency($payment->tax_value);
  578. })
  579. ->editColumn('tax_percent', function (Payment $payment) {
  580. return $payment->tax_percent.' %';
  581. })
  582. ->editColumn('total_price', function (Payment $payment) {
  583. return $payment->formatToCurrency($payment->total_price);
  584. })
  585. ->editColumn('created_at', function (Payment $payment) {
  586. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  587. })
  588. ->addColumn('actions', function (Payment $payment) {
  589. 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>';
  590. })
  591. ->rawColumns(['actions', 'user'])
  592. ->make(true);
  593. }
  594. }