PaymentController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Events\UserUpdateCreditsEvent;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\Configuration;
  6. use App\Models\Payment;
  7. use App\Models\CreditProduct;
  8. use App\Models\User;
  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\Log;
  19. use PayPalCheckoutSdk\Core\PayPalHttpClient;
  20. use PayPalCheckoutSdk\Core\ProductionEnvironment;
  21. use PayPalCheckoutSdk\Core\SandboxEnvironment;
  22. use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
  23. use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
  24. use PayPalHttp\HttpException;
  25. use Stripe\Stripe;
  26. class PaymentController extends Controller
  27. {
  28. /**
  29. * @return Application|Factory|View
  30. */
  31. public function index()
  32. {
  33. return view('admin.payments.index')->with([
  34. 'payments' => Payment::paginate(15)
  35. ]);
  36. }
  37. /**
  38. * @param Request $request
  39. * @param CreditProduct $creditProduct
  40. * @return Application|Factory|View
  41. */
  42. public function checkOut(Request $request, CreditProduct $creditProduct)
  43. {
  44. return view('store.checkout')->with([
  45. 'product' => $creditProduct,
  46. 'taxvalue' => $creditProduct->getTaxValue(),
  47. 'taxpercent' => $creditProduct->getTaxPercent(),
  48. 'total' => $creditProduct->getTotalPrice()
  49. ]);
  50. }
  51. /**
  52. * @param Request $request
  53. * @param CreditProduct $creditProduct
  54. * @return RedirectResponse
  55. */
  56. public function PaypalPay(Request $request, CreditProduct $creditProduct)
  57. {
  58. $request = new OrdersCreateRequest();
  59. $request->prefer('return=representation');
  60. $request->body = [
  61. "intent" => "CAPTURE",
  62. "purchase_units" => [
  63. [
  64. "reference_id" => uniqid(),
  65. "description" => $creditProduct->description,
  66. "amount" => [
  67. "value" => $creditProduct->getTotalPrice(),
  68. 'currency_code' => strtoupper($creditProduct->currency_code),
  69. 'breakdown' => [
  70. 'item_total' =>
  71. [
  72. 'currency_code' => strtoupper($creditProduct->currency_code),
  73. 'value' => $creditProduct->price,
  74. ],
  75. 'tax_total' =>
  76. [
  77. 'currency_code' => strtoupper($creditProduct->currency_code),
  78. 'value' => $creditProduct->getTaxValue(),
  79. ]
  80. ]
  81. ]
  82. ]
  83. ],
  84. "application_context" => [
  85. "cancel_url" => route('payment.Cancel'),
  86. "return_url" => route('payment.PaypalSuccess', ['product' => $creditProduct->id]),
  87. 'brand_name' => config('app.name', 'Laravel'),
  88. 'shipping_preference' => 'NO_SHIPPING'
  89. ]
  90. ];
  91. try {
  92. // Call API with your client and get a response for your call
  93. $response = $this->getPayPalClient()->execute($request);
  94. return redirect()->away($response->result->links[1]->href);
  95. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  96. } catch (HttpException $ex) {
  97. echo $ex->statusCode;
  98. dd(json_decode($ex->getMessage()));
  99. }
  100. }
  101. /**
  102. * @return PayPalHttpClient
  103. */
  104. protected function getPayPalClient()
  105. {
  106. $environment = env('APP_ENV') == 'local'
  107. ? new SandboxEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret())
  108. : new ProductionEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret());
  109. return new PayPalHttpClient($environment);
  110. }
  111. /**
  112. * @return string
  113. */
  114. protected function getPaypalClientId()
  115. {
  116. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_CLIENT_ID');
  117. }
  118. /**
  119. * @return string
  120. */
  121. protected function getPaypalClientSecret()
  122. {
  123. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_SECRET') : env('PAYPAL_SECRET');
  124. }
  125. /**
  126. * @param Request $laravelRequest
  127. */
  128. public function PaypalSuccess(Request $laravelRequest)
  129. {
  130. /** @var CreditProduct $creditProduct */
  131. $creditProduct = CreditProduct::findOrFail($laravelRequest->input('product'));
  132. /** @var User $user */
  133. $user = Auth::user();
  134. $request = new OrdersCaptureRequest($laravelRequest->input('token'));
  135. $request->prefer('return=representation');
  136. try {
  137. // Call API with your client and get a response for your call
  138. $response = $this->getPayPalClient()->execute($request);
  139. if ($response->statusCode == 201 || $response->statusCode == 200) {
  140. //update credits
  141. $user->increment('credits', $creditProduct->quantity);
  142. //update server limit
  143. if (Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  144. if ($user->server_limit < Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  145. $user->update(['server_limit' => Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  146. }
  147. }
  148. //update role
  149. if ($user->role == 'member') {
  150. $user->update(['role' => 'client']);
  151. }
  152. //store payment
  153. $payment = Payment::create([
  154. 'user_id' => $user->id,
  155. 'payment_id' => $response->result->id,
  156. 'payment_method' => 'paypal',
  157. 'type' => 'Credits',
  158. 'status' => 'paid',
  159. 'amount' => $creditProduct->quantity,
  160. 'price' => $creditProduct->price,
  161. 'tax_value' => $creditProduct->getTaxValue(),
  162. 'tax_percent' => $creditProduct->getTaxPercent(),
  163. 'total_price' => $creditProduct->getTotalPrice(),
  164. 'currency_code' => $creditProduct->currency_code,
  165. ]);
  166. //payment notification
  167. $user->notify(new ConfirmPaymentNotification($payment));
  168. event(new UserUpdateCreditsEvent($user));
  169. //redirect back to home
  170. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  171. }
  172. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  173. if (env('APP_ENV') == 'local') {
  174. dd($response);
  175. } else {
  176. abort(500);
  177. }
  178. } catch (HttpException $ex) {
  179. if (env('APP_ENV') == 'local') {
  180. echo $ex->statusCode;
  181. dd($ex->getMessage());
  182. } else {
  183. abort(422);
  184. }
  185. }
  186. }
  187. /**
  188. * @param Request $request
  189. */
  190. public function Cancel(Request $request)
  191. {
  192. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  193. }
  194. /**
  195. * @param Request $request
  196. * @param CreditProduct $creditProduct
  197. * @return RedirectResponse
  198. */
  199. public function StripePay(Request $request, CreditProduct $creditProduct)
  200. {
  201. $stripeClient = $this->getStripeClient();
  202. $request = $stripeClient->checkout->sessions->create([
  203. 'line_items' => [
  204. [
  205. 'price_data' => [
  206. 'currency' => $creditProduct->currency_code,
  207. 'product_data' => [
  208. 'name' => $creditProduct->display,
  209. 'description' => $creditProduct->description,
  210. ],
  211. 'unit_amount_decimal' => round($creditProduct->price * 100, 2),
  212. ],
  213. 'quantity' => 1,
  214. ],
  215. [
  216. 'price_data' => [
  217. 'currency' => $creditProduct->currency_code,
  218. 'product_data' => [
  219. 'name' => 'Product Tax',
  220. 'description' => $creditProduct->getTaxPercent() . "%",
  221. ],
  222. 'unit_amount_decimal' => round($creditProduct->getTaxValue(), 2) * 100,
  223. ],
  224. 'quantity' => 1,
  225. ]
  226. ],
  227. 'mode' => 'payment',
  228. "payment_method_types" => str_getcsv(env('STRIPE_METHODS')),
  229. 'success_url' => route('payment.StripeSuccess', ['product' => $creditProduct->id]) . '&session_id={CHECKOUT_SESSION_ID}',
  230. 'cancel_url' => route('payment.Cancel'),
  231. ]);
  232. return redirect($request->url, 303);
  233. }
  234. /**
  235. * @param Request $request
  236. */
  237. public function StripeSuccess(Request $request)
  238. {
  239. /** @var CreditProduct $creditProduct */
  240. $creditProduct = CreditProduct::findOrFail($request->input('product'));
  241. /** @var User $user */
  242. $user = Auth::user();
  243. $stripeClient = $this->getStripeClient();
  244. try {
  245. //get stripe data
  246. $paymentSession = $stripeClient->checkout->sessions->retrieve($request->input('session_id'));
  247. $paymentIntent = $stripeClient->paymentIntents->retrieve($paymentSession->payment_intent);
  248. //get DB entry of this payment ID if existing
  249. $paymentDbEntry = Payment::where('payment_id', $paymentSession->payment_intent)->count();
  250. // check if payment is 100% completed and payment does not exist in db already
  251. if ($paymentSession->status == "complete" && $paymentIntent->status == "succeeded" && $paymentDbEntry == 0) {
  252. //update credits
  253. $user->increment('credits', $creditProduct->quantity);
  254. //update server limit
  255. if (Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  256. if ($user->server_limit < Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  257. $user->update(['server_limit' => Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  258. }
  259. }
  260. //update role
  261. if ($user->role == 'member') {
  262. $user->update(['role' => 'client']);
  263. }
  264. //store paid payment
  265. $payment = Payment::create([
  266. 'user_id' => $user->id,
  267. 'payment_id' => $paymentSession->payment_intent,
  268. 'payment_method' => 'stripe',
  269. 'type' => 'Credits',
  270. 'status' => 'paid',
  271. 'amount' => $creditProduct->quantity,
  272. 'price' => $creditProduct->price,
  273. 'tax_value' => $creditProduct->getTaxValue(),
  274. 'total_price' => $creditProduct->getTotalPrice(),
  275. 'tax_percent' => $creditProduct->getTaxPercent(),
  276. 'currency_code' => $creditProduct->currency_code,
  277. ]);
  278. //payment notification
  279. $user->notify(new ConfirmPaymentNotification($payment));
  280. event(new UserUpdateCreditsEvent($user));
  281. //redirect back to home
  282. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  283. } else {
  284. if ($paymentIntent->status == "processing") {
  285. //store processing payment
  286. $payment = Payment::create([
  287. 'user_id' => $user->id,
  288. 'payment_id' => $paymentSession->payment_intent,
  289. 'payment_method' => 'stripe',
  290. 'type' => 'Credits',
  291. 'status' => 'processing',
  292. 'amount' => $creditProduct->quantity,
  293. 'price' => $creditProduct->price,
  294. 'tax_value' => $creditProduct->getTaxValue(),
  295. 'total_price' => $creditProduct->getTotalPrice(),
  296. 'tax_percent' => $creditProduct->getTaxPercent(),
  297. 'currency_code' => $creditProduct->currency_code,
  298. ]);
  299. //redirect back to home
  300. return redirect()->route('home')->with('success', __('Your payment is being processed!'));
  301. }
  302. if ($paymentDbEntry == 0 && $paymentIntent->status != "processing") {
  303. $stripeClient->paymentIntents->cancel($paymentIntent->id);
  304. //redirect back to home
  305. return redirect()->route('home')->with('success', __('Your payment has been canceled!'));
  306. } else {
  307. abort(402);
  308. }
  309. }
  310. } catch (HttpException $ex) {
  311. if (env('APP_ENV') == 'local') {
  312. echo $ex->statusCode;
  313. dd($ex->getMessage());
  314. } else {
  315. abort(422);
  316. }
  317. }
  318. }
  319. /**
  320. * @param Request $request
  321. */
  322. protected function handleStripePayment($paymentIntent)
  323. {
  324. try {
  325. // Get payment db entry
  326. $payment = Payment::where('payment_id', $paymentIntent->id)->first();
  327. $user = User::where('id', $payment->user_id)->first();
  328. if ($paymentIntent->status == 'succeeded' && $payment->status == 'processing') {
  329. // Increment User Credits
  330. $user->increment('credits', $payment->amount);
  331. //update server limit
  332. if (Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  333. if ($user->server_limit < Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  334. $user->update(['server_limit' => Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  335. }
  336. }
  337. //update role
  338. if ($user->role == 'member') {
  339. $user->update(['role' => 'client']);
  340. }
  341. //update payment db entry status
  342. $payment->update(['status' => 'paid']);
  343. //payment notification
  344. $user->notify(new ConfirmPaymentNotification($payment));
  345. event(new UserUpdateCreditsEvent($user));
  346. }
  347. } catch (HttpException $ex) {
  348. abort(422);
  349. }
  350. }
  351. /**
  352. * @param Request $request
  353. */
  354. public function StripeWebhooks(Request $request)
  355. {
  356. \Stripe\Stripe::setApiKey($this->getStripeSecret());
  357. try {
  358. $payload = @file_get_contents('php://input');
  359. $sig_header = $request->header('Stripe-Signature');
  360. $event = null;
  361. $event = \Stripe\Webhook::constructEvent(
  362. $payload,
  363. $sig_header,
  364. $this->getStripeEndpointSecret()
  365. );
  366. } catch (\UnexpectedValueException $e) {
  367. // Invalid payload
  368. abort(400);
  369. } catch (\Stripe\Exception\SignatureVerificationException $e) {
  370. // Invalid signature
  371. abort(400);
  372. }
  373. // Handle the event
  374. switch ($event->type) {
  375. case 'payment_intent.succeeded':
  376. $paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
  377. $this->handleStripePayment($paymentIntent);
  378. break;
  379. case 'payment_method.attached':
  380. $paymentMethod = $event->data->object; // contains a \Stripe\PaymentMethod
  381. error_log($paymentMethod);
  382. break;
  383. // ... handle other event types
  384. default:
  385. echo 'Received unknown event type ' . $event->type;
  386. }
  387. }
  388. /**
  389. * @return \Stripe\StripeClient
  390. */
  391. protected function getStripeClient()
  392. {
  393. return new \Stripe\StripeClient($this->getStripeSecret());
  394. }
  395. /**
  396. * @return string
  397. */
  398. protected function getStripeSecret()
  399. {
  400. return env('APP_ENV') == 'local'
  401. ? env('STRIPE_TEST_SECRET')
  402. : env('STRIPE_SECRET');
  403. }
  404. /**
  405. * @return string
  406. */
  407. protected function getStripeEndpointSecret()
  408. {
  409. return env('APP_ENV') == 'local'
  410. ? env('STRIPE_ENDPOINT_TEST_SECRET')
  411. : env('STRIPE_ENDPOINT_SECRET');
  412. }
  413. /**
  414. * @return JsonResponse|mixed
  415. * @throws Exception
  416. */
  417. public function dataTable()
  418. {
  419. $query = Payment::with('user');
  420. return datatables($query)
  421. ->editColumn('user', function (Payment $payment) {
  422. return $payment->user->name;
  423. })
  424. ->editColumn('price', function (Payment $payment) {
  425. return $payment->formatToCurrency($payment->price);
  426. })
  427. ->editColumn('tax_value', function (Payment $payment) {
  428. return $payment->formatToCurrency($payment->tax_value);
  429. })
  430. ->editColumn('tax_percent', function (Payment $payment) {
  431. return $payment->tax_percent . ' %';
  432. })
  433. ->editColumn('total_price', function (Payment $payment) {
  434. return $payment->formatToCurrency($payment->total_price);
  435. })
  436. ->editColumn('created_at', function (Payment $payment) {
  437. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  438. })
  439. ->make();
  440. }
  441. }