PaymentController.php 28 KB

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