PaymentController.php 8.0 KB

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