PaymentController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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 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. //redirect back to home
  286. return redirect()->route('home')->with('success', __('Your payment is being processed!'));
  287. }
  288. if($paymentDbEntry == 0){
  289. $stripeClient->paymentIntents->cancel($paymentIntent->id);
  290. //redirect back to home
  291. return redirect()->route('home')->with('success', __('Your payment has been canceled!'));
  292. }else{
  293. abort(402);
  294. }
  295. }
  296. }catch (HttpException $ex) {
  297. if (env('APP_ENV') == 'local') {
  298. echo $ex->statusCode;
  299. dd($ex->getMessage());
  300. } else {
  301. abort(422);
  302. }
  303. }
  304. }
  305. /**
  306. * @param Request $request
  307. */
  308. public function StripeWebhooks(Request $request)
  309. {
  310. \Stripe\Stripe::setApiKey($this->getStripeSecret());
  311. try {
  312. $payload = @file_get_contents('php://input');
  313. $sig_header = $request->header('Stripe-Signature');
  314. $event = null;
  315. $event = \Stripe\Webhook::constructEvent(
  316. $payload, $sig_header, $this->getStripeEndpointSecret()
  317. );
  318. } catch(\UnexpectedValueException $e) {
  319. // Invalid payload
  320. abort(400);
  321. } catch(\Stripe\Exception\SignatureVerificationException $e) {
  322. // Invalid signature
  323. abort(400);
  324. }
  325. // Handle the event
  326. switch ($event->type) {
  327. case 'payment_intent.succeeded':
  328. $paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
  329. error_log($paymentIntent->status);
  330. break;
  331. case 'payment_method.attached':
  332. $paymentMethod = $event->data->object; // contains a \Stripe\PaymentMethod
  333. error_log($paymentMethod);
  334. break;
  335. // ... handle other event types
  336. default:
  337. echo 'Received unknown event type ' . $event->type;
  338. }
  339. }
  340. /**
  341. * @return \Stripe\StripeClient
  342. */
  343. protected function getStripeClient()
  344. {
  345. return new \Stripe\StripeClient($this->getStripeSecret());
  346. }
  347. /**
  348. * @return string
  349. */
  350. protected function getStripeSecret()
  351. {
  352. return env('APP_ENV') == 'local'
  353. ? env('STRIPE_TEST_SECRET')
  354. : env('STRIPE_SECRET');
  355. }
  356. /**
  357. * @return string
  358. */
  359. protected function getStripeEndpointSecret()
  360. {
  361. return env('APP_ENV') == 'local'
  362. ? env('STRIPE_ENDPOINT_TEST_SECRET')
  363. : env('STRIPE_ENDPOINT_SECRET');
  364. }
  365. /**
  366. * @return JsonResponse|mixed
  367. * @throws Exception
  368. */
  369. public function dataTable()
  370. {
  371. $query = Payment::with('user');
  372. return datatables($query)
  373. ->editColumn('user', function (Payment $payment) {
  374. return $payment->user->name;
  375. })
  376. ->editColumn('price', function (Payment $payment) {
  377. return $payment->formatToCurrency($payment->price);
  378. })
  379. ->editColumn('tax_value', function (Payment $payment) {
  380. return $payment->formatToCurrency($payment->tax_value);
  381. })
  382. ->editColumn('tax_percent', function (Payment $payment) {
  383. return $payment->tax_percent . ' %';
  384. })
  385. ->editColumn('total_price', function (Payment $payment) {
  386. return $payment->formatToCurrency($payment->total_price);
  387. })
  388. ->editColumn('created_at', function (Payment $payment) {
  389. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  390. })
  391. ->make();
  392. }
  393. }