PaymentController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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\Product;
  9. use App\Models\User;
  10. use App\Notifications\ConfirmPaymentNotification;
  11. use Exception;
  12. use Illuminate\Contracts\Foundation\Application;
  13. use Illuminate\Contracts\View\Factory;
  14. use Illuminate\Contracts\View\View;
  15. use Illuminate\Http\JsonResponse;
  16. use Illuminate\Http\RedirectResponse;
  17. use Illuminate\Http\Request;
  18. use Illuminate\Support\Facades\Auth;
  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' => $response->result->status,
  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_intent_data' => [
  229. 'capture_method' => 'manual',
  230. ],
  231. 'success_url' => route('payment.StripeSuccess', ['product' => $creditProduct->id]).'&session_id={CHECKOUT_SESSION_ID}',
  232. 'cancel_url' => route('payment.Cancel'),
  233. ]);
  234. return redirect($request->url, 303);
  235. }
  236. /**
  237. * @param Request $request
  238. */
  239. public function StripeSuccess(Request $request)
  240. {
  241. /** @var CreditProduct $creditProduct */
  242. $creditProduct = CreditProduct::findOrFail($request->input('product'));
  243. /** @var User $user */
  244. $user = Auth::user();
  245. $stripeClient = $this->getStripeClient();
  246. try{
  247. $paymentSession = $stripeClient->checkout->sessions->retrieve($request->input('session_id'));
  248. $capturedPaymentIntent = $stripeClient->paymentIntents->capture($paymentSession->payment_intent);
  249. if ($capturedPaymentIntent->status == "succeeded") {
  250. //update credits
  251. $user->increment('credits', $creditProduct->quantity);
  252. //update server limit
  253. if (Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  254. if ($user->server_limit < Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  255. $user->update(['server_limit' => Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  256. }
  257. }
  258. //update role
  259. if ($user->role == 'member') {
  260. $user->update(['role' => 'client']);
  261. }
  262. //store payment
  263. $payment = Payment::create([
  264. 'user_id' => $user->id,
  265. 'payment_id' => $capturedPaymentIntent->id,
  266. 'payment_method' => 'stripe',
  267. 'type' => 'Credits',
  268. 'status' => $capturedPaymentIntent->status,
  269. 'amount' => $creditProduct->quantity,
  270. 'price' => $creditProduct->price,
  271. 'tax_value' => $creditProduct->getTaxValue(),
  272. 'total_price' => $creditProduct->getTotalPrice(),
  273. 'tax_percent' => $creditProduct->getTaxPercent(),
  274. 'currency_code' => $creditProduct->currency_code,
  275. ]);
  276. //payment notification
  277. $user->notify(new ConfirmPaymentNotification($payment));
  278. event(new UserUpdateCreditsEvent($user));
  279. //redirect back to home
  280. return redirect()->route('home')->with('success', 'Your credit balance has been increased!');
  281. }
  282. }catch (HttpException $ex) {
  283. if (env('APP_ENV') == 'local') {
  284. echo $ex->statusCode;
  285. dd($ex->getMessage());
  286. } else {
  287. abort(422);
  288. }
  289. }
  290. }
  291. /**
  292. * @return StripeClient
  293. */
  294. protected function getStripeClient()
  295. {
  296. $environment = env('APP_ENV') == 'local'
  297. ? $this->getStripeSecret()
  298. : $this->getStripeSecret();
  299. return new \Stripe\StripeClient($environment);
  300. }
  301. /**
  302. * @return string
  303. */
  304. protected function getStripeClientId()
  305. {
  306. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_CLIENT_ID');
  307. }
  308. /**
  309. * @return string
  310. */
  311. protected function getStripeSecret()
  312. {
  313. return env('STRIPE_SECRET');
  314. }
  315. /**
  316. * @return JsonResponse|mixed
  317. * @throws Exception
  318. */
  319. public function dataTable()
  320. {
  321. $query = Payment::with('user');
  322. return datatables($query)
  323. ->editColumn('user', function (Payment $payment) {
  324. return $payment->user->name;
  325. })
  326. ->editColumn('price', function (Payment $payment) {
  327. return $payment->formatToCurrency($payment->price);
  328. })
  329. ->editColumn('tax_value', function (Payment $payment) {
  330. return $payment->formatToCurrency($payment->tax_value);
  331. })
  332. ->editColumn('total_price', function (Payment $payment) {
  333. return $payment->formatToCurrency($payment->total_price);
  334. })
  335. ->editColumn('created_at', function (Payment $payment) {
  336. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  337. })
  338. ->make();
  339. }
  340. }