PaymentController.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. 'taxvalue' => $paypalProduct->getTaxValue(),
  46. 'taxpercent' => $paypalProduct->getTaxPercent(),
  47. 'total' => $paypalProduct->getTotalPrice()
  48. ]);
  49. }
  50. /**
  51. * @param Request $request
  52. * @param PaypalProduct $paypalProduct
  53. * @return RedirectResponse
  54. */
  55. public function pay(Request $request, PaypalProduct $paypalProduct)
  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" => $paypalProduct->description,
  65. "amount" => [
  66. "value" => $paypalProduct->getTotalPrice(),
  67. 'currency_code' => strtoupper($paypalProduct->currency_code),
  68. 'breakdown' =>[
  69. 'item_total' =>
  70. [
  71. 'currency_code' => strtoupper($paypalProduct->currency_code),
  72. 'value' => $paypalProduct->price,
  73. ],
  74. 'tax_total' =>
  75. [
  76. 'currency_code' => strtoupper($paypalProduct->currency_code),
  77. 'value' => $paypalProduct->getTaxValue(),
  78. ]
  79. ]
  80. ]
  81. ]
  82. ],
  83. "application_context" => [
  84. "cancel_url" => route('payment.cancel'),
  85. "return_url" => route('payment.success', ['product' => $paypalProduct->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->getClientId(), $this->getClientSecret())
  107. : new ProductionEnvironment($this->getClientId(), $this->getClientSecret());
  108. return new PayPalHttpClient($environment);
  109. }
  110. /**
  111. * @return string
  112. */
  113. protected function getClientId()
  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 getClientSecret()
  121. {
  122. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_SECRET') : env('PAYPAL_SECRET');
  123. }
  124. /**
  125. * @param Request $laravelRequest
  126. */
  127. public function success(Request $laravelRequest)
  128. {
  129. /** @var PaypalProduct $paypalProduct */
  130. $paypalProduct = PaypalProduct::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', $paypalProduct->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. 'payer_id' => $laravelRequest->input('PayerID'),
  156. 'type' => 'Credits',
  157. 'status' => $response->result->status,
  158. 'amount' => $paypalProduct->quantity,
  159. 'price' => $paypalProduct->price,
  160. 'tax_value' => $paypalProduct->getTaxValue(),
  161. 'tax_percent' => $paypalProduct->getTaxPercent(),
  162. 'total_price' => $paypalProduct->getTotalPrice(),
  163. 'currency_code' => $paypalProduct->currency_code,
  164. 'payer' => json_encode($response->result->payer),
  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. * @return JsonResponse|mixed
  196. * @throws Exception
  197. */
  198. public function dataTable()
  199. {
  200. $query = Payment::with('user');
  201. return datatables($query)
  202. ->editColumn('user', function (Payment $payment) {
  203. return $payment->user->name;
  204. })
  205. ->editColumn('price', function (Payment $payment) {
  206. return $payment->formatToCurrency($payment->price);
  207. })
  208. ->editColumn('tax_value', function (Payment $payment) {
  209. return $payment->formatToCurrency($payment->tax_value);
  210. })
  211. ->editColumn('total_price', function (Payment $payment) {
  212. return $payment->formatToCurrency($payment->total_price);
  213. })
  214. ->editColumn('created_at', function (Payment $payment) {
  215. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  216. })
  217. ->make();
  218. }
  219. }