PaymentController.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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\PaypalProduct;
  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. 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 PaypalProduct $paypalProduct
  39. * @return Application|Factory|View
  40. */
  41. public function checkOut(Request $request, PaypalProduct $paypalProduct)
  42. {
  43. return view('store.checkout')->with([
  44. 'product' => $paypalProduct
  45. ]);
  46. }
  47. /**
  48. * @param Request $request
  49. * @param PaypalProduct $paypalProduct
  50. * @return RedirectResponse
  51. */
  52. public function pay(Request $request, PaypalProduct $paypalProduct)
  53. {
  54. $request = new OrdersCreateRequest();
  55. $request->prefer('return=representation');
  56. $request->body = [
  57. "intent" => "CAPTURE",
  58. "purchase_units" => [
  59. [
  60. "reference_id" => uniqid(),
  61. "description" => $paypalProduct->description,
  62. "amount" => [
  63. "value" => $paypalProduct->price,
  64. "currency_code" => strtoupper($paypalProduct->currency_code)
  65. ]
  66. ]
  67. ],
  68. "application_context" => [
  69. "cancel_url" => route('payment.cancel'),
  70. "return_url" => route('payment.success', ['product' => $paypalProduct->id]),
  71. 'brand_name' => config('app.name', 'Laravel'),
  72. 'shipping_preference' => 'NO_SHIPPING'
  73. ]
  74. ];
  75. try {
  76. // Call API with your client and get a response for your call
  77. $response = $this->getPayPalClient()->execute($request);
  78. return redirect()->away($response->result->links[1]->href);
  79. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  80. } catch (HttpException $ex) {
  81. echo $ex->statusCode;
  82. dd(json_decode($ex->getMessage()));
  83. }
  84. }
  85. /**
  86. * @return PayPalHttpClient
  87. */
  88. protected function getPayPalClient()
  89. {
  90. $environment = env('APP_ENV') == 'local'
  91. ? new SandboxEnvironment($this->getClientId(), $this->getClientSecret())
  92. : new ProductionEnvironment($this->getClientId(), $this->getClientSecret());
  93. return new PayPalHttpClient($environment);
  94. }
  95. /**
  96. * @return string
  97. */
  98. protected function getClientId()
  99. {
  100. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_CLIENT_ID');
  101. }
  102. /**
  103. * @return string
  104. */
  105. protected function getClientSecret()
  106. {
  107. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_SECRET') : env('PAYPAL_SECRET');
  108. }
  109. /**
  110. * @param Request $laravelRequest
  111. */
  112. public function success(Request $laravelRequest)
  113. {
  114. /** @var PaypalProduct $paypalProduct */
  115. $paypalProduct = PaypalProduct::findOrFail($laravelRequest->input('product'));
  116. /** @var User $user */
  117. $user = Auth::user();
  118. $request = new OrdersCaptureRequest($laravelRequest->input('token'));
  119. $request->prefer('return=representation');
  120. try {
  121. // Call API with your client and get a response for your call
  122. $response = $this->getPayPalClient()->execute($request);
  123. if ($response->statusCode == 201 || $response->statusCode == 200) {
  124. //update credits
  125. $user->increment('credits', $paypalProduct->quantity);
  126. //update server limit
  127. if (Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  128. if ($user->server_limit < Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  129. $user->update(['server_limit' => Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  130. }
  131. }
  132. //update role
  133. if ($user->role == 'member') {
  134. $user->update(['role' => 'client']);
  135. }
  136. //store payment
  137. $payment = Payment::create([
  138. 'user_id' => $user->id,
  139. 'payment_id' => $response->result->id,
  140. 'payer_id' => $laravelRequest->input('PayerID'),
  141. 'type' => 'Credits',
  142. 'status' => $response->result->status,
  143. 'amount' => $paypalProduct->quantity,
  144. 'price' => $paypalProduct->price,
  145. 'currency_code' => $paypalProduct->currency_code,
  146. 'payer' => json_encode($response->result->payer),
  147. ]);
  148. //payment notification
  149. $user->notify(new ConfirmPaymentNotification($payment));
  150. event(new UserUpdateCreditsEvent($user));
  151. //redirect back to home
  152. return redirect()->route('home')->with('success', 'Your credit balance has been increased!');
  153. }
  154. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  155. if (env('APP_ENV') == 'local') {
  156. dd($response);
  157. } else {
  158. abort(500);
  159. }
  160. } catch (HttpException $ex) {
  161. if (env('APP_ENV') == 'local') {
  162. echo $ex->statusCode;
  163. dd($ex->getMessage());
  164. } else {
  165. abort(422);
  166. }
  167. }
  168. }
  169. /**
  170. * @param Request $request
  171. */
  172. public function cancel(Request $request)
  173. {
  174. return redirect()->route('store.index')->with('success', 'Payment was Cannceled');
  175. }
  176. /**
  177. * @return JsonResponse|mixed
  178. * @throws Exception
  179. */
  180. public function dataTable()
  181. {
  182. $query = Payment::with('user');
  183. return datatables($query)
  184. ->editColumn('user', function (Payment $payment) {
  185. return $payment->user->name;
  186. })
  187. ->editColumn('price', function (Payment $payment) {
  188. return $payment->formatCurrency();
  189. })
  190. ->editColumn('created_at', function (Payment $payment) {
  191. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  192. })
  193. ->make();
  194. }
  195. }