PaymentController.php 11 KB

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