PaymentController.php 8.6 KB

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