PaymentController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. echo $creditProduct->currency_code;
  59. $request = new OrdersCreateRequest();
  60. $request->prefer('return=representation');
  61. $request->body = [
  62. "intent" => "CAPTURE",
  63. "purchase_units" => [
  64. [
  65. "reference_id" => uniqid(),
  66. "description" => $creditProduct->description,
  67. "amount" => [
  68. "value" => $creditProduct->getTotalPrice(),
  69. 'currency_code' => strtoupper($creditProduct->currency_code),
  70. 'breakdown' =>[
  71. 'item_total' =>
  72. [
  73. 'currency_code' => strtoupper($creditProduct->currency_code),
  74. 'value' => $creditProduct->price,
  75. ],
  76. 'tax_total' =>
  77. [
  78. 'currency_code' => strtoupper($creditProduct->currency_code),
  79. 'value' => $creditProduct->getTaxValue(),
  80. ]
  81. ]
  82. ]
  83. ]
  84. ],
  85. "application_context" => [
  86. "cancel_url" => route('payment.PaypalCancel'),
  87. "return_url" => route('payment.PaypalSuccess', ['product' => $creditProduct->id]),
  88. 'brand_name' => config('app.name', 'Laravel'),
  89. 'shipping_preference' => 'NO_SHIPPING'
  90. ]
  91. ];
  92. try {
  93. // Call API with your client and get a response for your call
  94. $response = $this->getPayPalClient()->execute($request);
  95. return redirect()->away($response->result->links[1]->href);
  96. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  97. } catch (HttpException $ex) {
  98. echo $ex->statusCode;
  99. dd(json_decode($ex->getMessage()));
  100. }
  101. }
  102. /**
  103. * @return PayPalHttpClient
  104. */
  105. protected function getPayPalClient()
  106. {
  107. $environment = env('APP_ENV') == 'local'
  108. ? new SandboxEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret())
  109. : new ProductionEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret());
  110. return new PayPalHttpClient($environment);
  111. }
  112. /**
  113. * @return string
  114. */
  115. protected function getPaypalClientId()
  116. {
  117. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_CLIENT_ID');
  118. }
  119. /**
  120. * @return string
  121. */
  122. protected function getPaypalClientSecret()
  123. {
  124. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_SECRET') : env('PAYPAL_SECRET');
  125. }
  126. /**
  127. * @param Request $laravelRequest
  128. */
  129. public function PaypalSuccess(Request $laravelRequest)
  130. {
  131. /** @var CreditProduct $creditProduct */
  132. $creditProduct = CreditProduct::findOrFail($laravelRequest->input('product'));
  133. /** @var User $user */
  134. $user = Auth::user();
  135. $request = new OrdersCaptureRequest($laravelRequest->input('token'));
  136. $request->prefer('return=representation');
  137. try {
  138. // Call API with your client and get a response for your call
  139. $response = $this->getPayPalClient()->execute($request);
  140. if ($response->statusCode == 201 || $response->statusCode == 200) {
  141. //update credits
  142. $user->increment('credits', $creditProduct->quantity);
  143. //update server limit
  144. if (Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  145. if ($user->server_limit < Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  146. $user->update(['server_limit' => Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  147. }
  148. }
  149. //update role
  150. if ($user->role == 'member') {
  151. $user->update(['role' => 'client']);
  152. }
  153. //store payment
  154. $payment = Payment::create([
  155. 'user_id' => $user->id,
  156. 'payment_id' => $response->result->id,
  157. 'payer_id' => $laravelRequest->input('PayerID'),
  158. 'type' => 'Credits',
  159. 'status' => $response->result->status,
  160. 'amount' => $creditProduct->quantity,
  161. 'price' => $creditProduct->price,
  162. 'tax_value' => $creditProduct->getTaxValue(),
  163. 'tax_percent' => $creditProduct->getTaxPercent(),
  164. 'total_price' => $creditProduct->getTotalPrice(),
  165. 'currency_code' => $creditProduct->currency_code,
  166. 'payer' => json_encode($response->result->payer),
  167. ]);
  168. //payment notification
  169. $user->notify(new ConfirmPaymentNotification($payment));
  170. event(new UserUpdateCreditsEvent($user));
  171. //redirect back to home
  172. return redirect()->route('home')->with('success', 'Your credit balance has been increased!');
  173. }
  174. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  175. if (env('APP_ENV') == 'local') {
  176. dd($response);
  177. } else {
  178. abort(500);
  179. }
  180. } catch (HttpException $ex) {
  181. if (env('APP_ENV') == 'local') {
  182. echo $ex->statusCode;
  183. dd($ex->getMessage());
  184. } else {
  185. abort(422);
  186. }
  187. }
  188. }
  189. /**
  190. * @param Request $request
  191. */
  192. public function PaypalCancel(Request $request)
  193. {
  194. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  195. }
  196. /**
  197. * @param Request $request
  198. * @param CreditProduct $creditProduct
  199. * @return RedirectResponse
  200. */
  201. public function StripePay(Request $request, CreditProduct $creditProduct)
  202. {
  203. \Stripe\Stripe::setApiKey('sk_test_51Js6U8J2KSABgZztx8QWiohacnzGyIlpOk48DfSoUWPW8mhqLzxcQ5B9a1Wiz8jCC4Xfp3QeBDTsuSU7hkXEUksW00JyN08hoU');
  204. $request = \Stripe\Checkout\Session::create([
  205. 'line_items' => [
  206. [
  207. 'price_data' => [
  208. 'currency' => $creditProduct->currency_code,
  209. 'product_data' => [
  210. 'name' => $creditProduct->display,
  211. 'description' => $creditProduct->description,
  212. ],
  213. 'unit_amount_decimal' => round($creditProduct->price*100, 2),
  214. ],
  215. 'quantity' => 1,
  216. ],
  217. [
  218. 'price_data' => [
  219. 'currency' => $creditProduct->currency_code,
  220. 'product_data' => [
  221. 'name' => 'Product Tax',
  222. 'description' => $creditProduct->getTaxPercent() . "%",
  223. ],
  224. 'unit_amount_decimal' => round($creditProduct->getTaxValue(), 2)*100,
  225. ],
  226. 'quantity' => 1,
  227. ]
  228. ],
  229. 'mode' => 'payment',
  230. 'success_url' => route('payment.PaypalCancel'),
  231. 'cancel_url' => route('payment.PaypalCancel'),
  232. ]);
  233. return redirect($request->url, 303);
  234. }
  235. /**
  236. * @return string
  237. */
  238. protected function getStripeClientId()
  239. {
  240. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_CLIENT_ID');
  241. }
  242. /**
  243. * @return string
  244. */
  245. protected function getStripeClientSecret()
  246. {
  247. return env('STRIPE_SECRET');
  248. }
  249. /**
  250. * @return JsonResponse|mixed
  251. * @throws Exception
  252. */
  253. public function dataTable()
  254. {
  255. $query = Payment::with('user');
  256. return datatables($query)
  257. ->editColumn('user', function (Payment $payment) {
  258. return $payment->user->name;
  259. })
  260. ->editColumn('price', function (Payment $payment) {
  261. return $payment->formatToCurrency($payment->price);
  262. })
  263. ->editColumn('tax_value', function (Payment $payment) {
  264. return $payment->formatToCurrency($payment->tax_value);
  265. })
  266. ->editColumn('total_price', function (Payment $payment) {
  267. return $payment->formatToCurrency($payment->total_price);
  268. })
  269. ->editColumn('created_at', function (Payment $payment) {
  270. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  271. })
  272. ->make();
  273. }
  274. }