PaymentController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 PayPalCheckoutSdk\Core\PayPalHttpClient;
  19. use PayPalCheckoutSdk\Core\ProductionEnvironment;
  20. use PayPalCheckoutSdk\Core\SandboxEnvironment;
  21. use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
  22. use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
  23. use PayPalHttp\HttpException;
  24. use Stripe\Stripe;
  25. class PaymentController extends Controller
  26. {
  27. /**
  28. * @return Application|Factory|View
  29. */
  30. public function index()
  31. {
  32. return view('admin.payments.index')->with([
  33. 'payments' => Payment::paginate(15)
  34. ]);
  35. }
  36. /**
  37. * @param Request $request
  38. * @param CreditProduct $creditProduct
  39. * @return Application|Factory|View
  40. */
  41. public function checkOut(Request $request, CreditProduct $creditProduct)
  42. {
  43. return view('store.checkout')->with([
  44. 'product' => $creditProduct,
  45. 'taxvalue' => $creditProduct->getTaxValue(),
  46. 'taxpercent' => $creditProduct->getTaxPercent(),
  47. 'total' => $creditProduct->getTotalPrice()
  48. ]);
  49. }
  50. /**
  51. * @param Request $request
  52. * @param CreditProduct $creditProduct
  53. * @return RedirectResponse
  54. */
  55. public function PaypalPay(Request $request, CreditProduct $creditProduct)
  56. {
  57. $request = new OrdersCreateRequest();
  58. $request->prefer('return=representation');
  59. $request->body = [
  60. "intent" => "CAPTURE",
  61. "purchase_units" => [
  62. [
  63. "reference_id" => uniqid(),
  64. "description" => $creditProduct->description,
  65. "amount" => [
  66. "value" => $creditProduct->getTotalPrice(),
  67. 'currency_code' => strtoupper($creditProduct->currency_code),
  68. 'breakdown' =>[
  69. 'item_total' =>
  70. [
  71. 'currency_code' => strtoupper($creditProduct->currency_code),
  72. 'value' => $creditProduct->price,
  73. ],
  74. 'tax_total' =>
  75. [
  76. 'currency_code' => strtoupper($creditProduct->currency_code),
  77. 'value' => $creditProduct->getTaxValue(),
  78. ]
  79. ]
  80. ]
  81. ]
  82. ],
  83. "application_context" => [
  84. "cancel_url" => route('payment.Cancel'),
  85. "return_url" => route('payment.PaypalSuccess', ['product' => $creditProduct->id]),
  86. 'brand_name' => config('app.name', 'Laravel'),
  87. 'shipping_preference' => 'NO_SHIPPING'
  88. ]
  89. ];
  90. try {
  91. // Call API with your client and get a response for your call
  92. $response = $this->getPayPalClient()->execute($request);
  93. return redirect()->away($response->result->links[1]->href);
  94. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  95. } catch (HttpException $ex) {
  96. echo $ex->statusCode;
  97. dd(json_decode($ex->getMessage()));
  98. }
  99. }
  100. /**
  101. * @return PayPalHttpClient
  102. */
  103. protected function getPayPalClient()
  104. {
  105. $environment = env('APP_ENV') == 'local'
  106. ? new SandboxEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret())
  107. : new ProductionEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret());
  108. return new PayPalHttpClient($environment);
  109. }
  110. /**
  111. * @return string
  112. */
  113. protected function getPaypalClientId()
  114. {
  115. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_CLIENT_ID');
  116. }
  117. /**
  118. * @return string
  119. */
  120. protected function getPaypalClientSecret()
  121. {
  122. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_SECRET') : env('PAYPAL_SECRET');
  123. }
  124. /**
  125. * @param Request $laravelRequest
  126. */
  127. public function PaypalSuccess(Request $laravelRequest)
  128. {
  129. /** @var CreditProduct $creditProduct */
  130. $creditProduct = CreditProduct::findOrFail($laravelRequest->input('product'));
  131. /** @var User $user */
  132. $user = Auth::user();
  133. $request = new OrdersCaptureRequest($laravelRequest->input('token'));
  134. $request->prefer('return=representation');
  135. try {
  136. // Call API with your client and get a response for your call
  137. $response = $this->getPayPalClient()->execute($request);
  138. if ($response->statusCode == 201 || $response->statusCode == 200) {
  139. //update credits
  140. $user->increment('credits', $creditProduct->quantity);
  141. //update server limit
  142. if (Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  143. if ($user->server_limit < Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  144. $user->update(['server_limit' => Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  145. }
  146. }
  147. //update role
  148. if ($user->role == 'member') {
  149. $user->update(['role' => 'client']);
  150. }
  151. //store payment
  152. $payment = Payment::create([
  153. 'user_id' => $user->id,
  154. 'payment_id' => $response->result->id,
  155. 'payment_method' => 'paypal',
  156. 'type' => 'Credits',
  157. 'status' => 'paid',
  158. 'amount' => $creditProduct->quantity,
  159. 'price' => $creditProduct->price,
  160. 'tax_value' => $creditProduct->getTaxValue(),
  161. 'tax_percent' => $creditProduct->getTaxPercent(),
  162. 'total_price' => $creditProduct->getTotalPrice(),
  163. 'currency_code' => $creditProduct->currency_code,
  164. ]);
  165. //payment notification
  166. $user->notify(new ConfirmPaymentNotification($payment));
  167. event(new UserUpdateCreditsEvent($user));
  168. //redirect back to home
  169. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  170. }
  171. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  172. if (env('APP_ENV') == 'local') {
  173. dd($response);
  174. } else {
  175. abort(500);
  176. }
  177. } catch (HttpException $ex) {
  178. if (env('APP_ENV') == 'local') {
  179. echo $ex->statusCode;
  180. dd($ex->getMessage());
  181. } else {
  182. abort(422);
  183. }
  184. }
  185. }
  186. /**
  187. * @param Request $request
  188. */
  189. public function Cancel(Request $request)
  190. {
  191. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  192. }
  193. /**
  194. * @param Request $request
  195. * @param CreditProduct $creditProduct
  196. * @return RedirectResponse
  197. */
  198. public function StripePay(Request $request, CreditProduct $creditProduct)
  199. {
  200. $stripeClient = $this->getStripeClient();
  201. $request = $stripeClient->checkout->sessions->create([
  202. 'line_items' => [
  203. [
  204. 'price_data' => [
  205. 'currency' => $creditProduct->currency_code,
  206. 'product_data' => [
  207. 'name' => $creditProduct->display,
  208. 'description' => $creditProduct->description,
  209. ],
  210. 'unit_amount_decimal' => round($creditProduct->price*100, 2),
  211. ],
  212. 'quantity' => 1,
  213. ],
  214. [
  215. 'price_data' => [
  216. 'currency' => $creditProduct->currency_code,
  217. 'product_data' => [
  218. 'name' => 'Product Tax',
  219. 'description' => $creditProduct->getTaxPercent() . "%",
  220. ],
  221. 'unit_amount_decimal' => round($creditProduct->getTaxValue(), 2)*100,
  222. ],
  223. 'quantity' => 1,
  224. ]
  225. ],
  226. 'mode' => 'payment',
  227. 'payment_intent_data' => [
  228. 'capture_method' => 'manual',
  229. ],
  230. 'success_url' => route('payment.StripeSuccess', ['product' => $creditProduct->id]).'&session_id={CHECKOUT_SESSION_ID}',
  231. 'cancel_url' => route('payment.Cancel'),
  232. ]);
  233. return redirect($request->url, 303);
  234. }
  235. /**
  236. * @param Request $request
  237. */
  238. public function StripeSuccess(Request $request)
  239. {
  240. /** @var CreditProduct $creditProduct */
  241. $creditProduct = CreditProduct::findOrFail($request->input('product'));
  242. /** @var User $user */
  243. $user = Auth::user();
  244. $stripeClient = $this->getStripeClient();
  245. try{
  246. $paymentSession = $stripeClient->checkout->sessions->retrieve($request->input('session_id'));
  247. $capturedPaymentIntent = $stripeClient->paymentIntents->capture($paymentSession->payment_intent);
  248. if ($capturedPaymentIntent->status == "succeeded") {
  249. //update credits
  250. $user->increment('credits', $creditProduct->quantity);
  251. //update server limit
  252. if (Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  253. if ($user->server_limit < Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  254. $user->update(['server_limit' => Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  255. }
  256. }
  257. //update role
  258. if ($user->role == 'member') {
  259. $user->update(['role' => 'client']);
  260. }
  261. //store payment
  262. $payment = Payment::create([
  263. 'user_id' => $user->id,
  264. 'payment_id' => $capturedPaymentIntent->id,
  265. 'payment_method' => 'stripe',
  266. 'type' => 'Credits',
  267. 'status' => 'paid',
  268. 'amount' => $creditProduct->quantity,
  269. 'price' => $creditProduct->price,
  270. 'tax_value' => $creditProduct->getTaxValue(),
  271. 'total_price' => $creditProduct->getTotalPrice(),
  272. 'tax_percent' => $creditProduct->getTaxPercent(),
  273. 'currency_code' => $creditProduct->currency_code,
  274. ]);
  275. //payment notification
  276. $user->notify(new ConfirmPaymentNotification($payment));
  277. event(new UserUpdateCreditsEvent($user));
  278. //redirect back to home
  279. return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
  280. }
  281. }catch (HttpException $ex) {
  282. if (env('APP_ENV') == 'local') {
  283. echo $ex->statusCode;
  284. dd($ex->getMessage());
  285. } else {
  286. abort(422);
  287. }
  288. }
  289. }
  290. /**
  291. * @return \Stripe\StripeClient
  292. */
  293. protected function getStripeClient()
  294. {
  295. return new \Stripe\StripeClient($this->getStripeSecret());
  296. }
  297. /**
  298. * @return string
  299. */
  300. protected function getStripeSecret()
  301. {
  302. return env('APP_ENV') == 'local'
  303. ? env('STRIPE_TEST_SECRET')
  304. : env('STRIPE_SECRET');
  305. }
  306. /**
  307. * @return JsonResponse|mixed
  308. * @throws Exception
  309. */
  310. public function dataTable()
  311. {
  312. $query = Payment::with('user');
  313. return datatables($query)
  314. ->editColumn('user', function (Payment $payment) {
  315. return $payment->user->name;
  316. })
  317. ->editColumn('price', function (Payment $payment) {
  318. return $payment->formatToCurrency($payment->price);
  319. })
  320. ->editColumn('tax_value', function (Payment $payment) {
  321. return $payment->formatToCurrency($payment->tax_value);
  322. })
  323. ->editColumn('tax_percent', function (Payment $payment) {
  324. return $payment->tax_percent . ' %';
  325. })
  326. ->editColumn('total_price', function (Payment $payment) {
  327. return $payment->formatToCurrency($payment->total_price);
  328. })
  329. ->editColumn('created_at', function (Payment $payment) {
  330. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  331. })
  332. ->make();
  333. }
  334. }