PaymentController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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\User;
  9. use App\Notifications\InvoiceNotification;
  10. use Exception;
  11. use Illuminate\Contracts\Foundation\Application;
  12. use Illuminate\Contracts\View\Factory;
  13. use Illuminate\Contracts\View\View;
  14. use Illuminate\Http\JsonResponse;
  15. use Illuminate\Http\RedirectResponse;
  16. use Illuminate\Http\Request;
  17. use Illuminate\Support\Facades\Auth;
  18. use Illuminate\Support\Facades\Storage;
  19. use LaravelDaily\Invoices\Classes\Buyer;
  20. use LaravelDaily\Invoices\Classes\InvoiceItem;
  21. use LaravelDaily\Invoices\Classes\Party;
  22. use LaravelDaily\Invoices\Invoice;
  23. use PayPalCheckoutSdk\Core\PayPalHttpClient;
  24. use PayPalCheckoutSdk\Core\ProductionEnvironment;
  25. use PayPalCheckoutSdk\Core\SandboxEnvironment;
  26. use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
  27. use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
  28. use PayPalHttp\HttpException;
  29. class PaymentController extends Controller
  30. {
  31. /**
  32. * @return Application|Factory|View
  33. */
  34. public function index()
  35. {
  36. return view('admin.payments.index')->with([
  37. 'payments' => Payment::paginate(15)
  38. ]);
  39. }
  40. /**
  41. * @param Request $request
  42. * @param PaypalProduct $paypalProduct
  43. * @return Application|Factory|View
  44. */
  45. public function checkOut(Request $request, PaypalProduct $paypalProduct)
  46. {
  47. return view('store.checkout')->with([
  48. 'product' => $paypalProduct,
  49. 'taxvalue' => $paypalProduct->getTaxValue(),
  50. 'taxpercent' => $paypalProduct->getTaxPercent(),
  51. 'total' => $paypalProduct->getTotalPrice()
  52. ]);
  53. }
  54. /**
  55. * @param Request $request
  56. * @param PaypalProduct $paypalProduct
  57. * @return RedirectResponse
  58. */
  59. public function pay(Request $request, PaypalProduct $paypalProduct)
  60. {
  61. $request = new OrdersCreateRequest();
  62. $request->prefer('return=representation');
  63. $request->body = [
  64. "intent" => "CAPTURE",
  65. "purchase_units" => [
  66. [
  67. "reference_id" => uniqid(),
  68. "description" => $paypalProduct->description,
  69. "amount" => [
  70. "value" => $paypalProduct->getTotalPrice(),
  71. 'currency_code' => strtoupper($paypalProduct->currency_code),
  72. 'breakdown' => [
  73. 'item_total' =>
  74. [
  75. 'currency_code' => strtoupper($paypalProduct->currency_code),
  76. 'value' => $paypalProduct->price,
  77. ],
  78. 'tax_total' =>
  79. [
  80. 'currency_code' => strtoupper($paypalProduct->currency_code),
  81. 'value' => $paypalProduct->getTaxValue(),
  82. ]
  83. ]
  84. ]
  85. ]
  86. ],
  87. "application_context" => [
  88. "cancel_url" => route('payment.cancel'),
  89. "return_url" => route('payment.success', ['product' => $paypalProduct->id]),
  90. 'brand_name' => config('app.name', 'Laravel'),
  91. 'shipping_preference' => 'NO_SHIPPING'
  92. ]
  93. ];
  94. try {
  95. // Call API with your client and get a response for your call
  96. $response = $this->getPayPalClient()->execute($request);
  97. return redirect()->away($response->result->links[1]->href);
  98. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  99. } catch (HttpException $ex) {
  100. echo $ex->statusCode;
  101. dd(json_decode($ex->getMessage()));
  102. }
  103. }
  104. /**
  105. * @return PayPalHttpClient
  106. */
  107. protected function getPayPalClient()
  108. {
  109. $environment = env('APP_ENV') == 'local'
  110. ? new SandboxEnvironment($this->getClientId(), $this->getClientSecret())
  111. : new ProductionEnvironment($this->getClientId(), $this->getClientSecret());
  112. return new PayPalHttpClient($environment);
  113. }
  114. /**
  115. * @return string
  116. */
  117. protected function getClientId()
  118. {
  119. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_CLIENT_ID') : env('PAYPAL_CLIENT_ID');
  120. }
  121. /**
  122. * @return string
  123. */
  124. protected function getClientSecret()
  125. {
  126. return env('APP_ENV') == 'local' ? env('PAYPAL_SANDBOX_SECRET') : env('PAYPAL_SECRET');
  127. }
  128. /**
  129. * @param Request $laravelRequest
  130. */
  131. public function success(Request $laravelRequest)
  132. {
  133. /** @var PaypalProduct $paypalProduct */
  134. $paypalProduct = PaypalProduct::findOrFail($laravelRequest->input('product'));
  135. /** @var User $user */
  136. $user = Auth::user();
  137. $request = new OrdersCaptureRequest($laravelRequest->input('token'));
  138. $request->prefer('return=representation');
  139. try {
  140. // Call API with your client and get a response for your call
  141. $response = $this->getPayPalClient()->execute($request);
  142. if ($response->statusCode == 201 || $response->statusCode == 200) {
  143. //update credits
  144. $user->increment('credits', $paypalProduct->quantity);
  145. //update server limit
  146. if (Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
  147. if ($user->server_limit < Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
  148. $user->update(['server_limit' => Configuration::getValueByKey('SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
  149. }
  150. }
  151. //update role
  152. if ($user->role == 'member') {
  153. $user->update(['role' => 'client']);
  154. }
  155. //store payment
  156. $payment = Payment::create([
  157. 'user_id' => $user->id,
  158. 'payment_id' => $response->result->id,
  159. 'payer_id' => $laravelRequest->input('PayerID'),
  160. 'type' => 'Credits',
  161. 'status' => $response->result->status,
  162. 'amount' => $paypalProduct->quantity,
  163. 'price' => $paypalProduct->price,
  164. 'tax_value' => $paypalProduct->getTaxValue(),
  165. 'tax_percent' => $paypalProduct->getTaxPercent(),
  166. 'total_price' => $paypalProduct->getTotalPrice(),
  167. 'currency_code' => $paypalProduct->currency_code,
  168. 'payer' => json_encode($response->result->payer),
  169. ]);
  170. event(new UserUpdateCreditsEvent($user));
  171. //create invoice
  172. $lastInvoiceID = \App\Models\invoice::where("invoice_name", "like", "%" . now()->format('mY') . "%")->max("id");
  173. $newInvoiceID = $lastInvoiceID + 1;
  174. $seller = new Party([
  175. 'name' => env("APP_NAME", "Controlpanel.gg"),
  176. 'phone' => env("COMPANY_PHONE", ""),
  177. 'address' => env("COMPANY_ADRESS", ""),
  178. 'vat' => env("COMPANY_VAT_ID", ""),
  179. 'custom_fields' => [
  180. 'E-Mail' => env("MAIL_FROM_ADDRESS", "company@mail.com"),
  181. "Web" => env("APP_URL", "https://controlpanel.gg")
  182. ],
  183. ]);
  184. $customer = new Buyer([
  185. 'name' => $user->name,
  186. 'custom_fields' => [
  187. 'E-Mail' => $user->email,
  188. 'Client ID' => $user->id,
  189. ],
  190. ]);
  191. $item = (new InvoiceItem())->title($paypalProduct->description)->pricePerUnit($paypalProduct->price);
  192. $invoice = Invoice::make()
  193. ->buyer($customer)
  194. ->seller($seller)
  195. ->discountByPercent(0)
  196. ->taxRate(floatval($paypalProduct->getTaxPercent()))
  197. ->shipping(0)
  198. ->addItem($item)
  199. ->status(__('invoices::invoice.paid'))
  200. ->series(now()->format('mY'))
  201. ->delimiter("-")
  202. ->sequence($newInvoiceID)
  203. ->serialNumberFormat(env("INVOICE_PREFIX", "INV") . '{DELIMITER}{SERIES}{SEQUENCE}')
  204. ->logo(public_path('vendor/invoices/logo.png'));
  205. //Save the invoice in "storage\app\invoice\USER_ID\YEAR"
  206. $invoice->filename = $invoice->getSerialNumber() . '.pdf';
  207. $invoice->render();
  208. Storage::disk("local")->put("invoice/" . $user->id . "/" . now()->format('Y') . "/" . $invoice->filename, $invoice->output);
  209. \App\Models\invoice::create([
  210. 'invoice_user' => $user->id,
  211. 'invoice_name' => $invoice->getSerialNumber(),
  212. 'payment_id' => $payment->payment_id,
  213. ]);
  214. //Send Invoice per Mail
  215. $user->notify(new InvoiceNotification($invoice, $user, $payment));
  216. //redirect back to home
  217. return redirect()->route('home')->with('success', 'Your credit balance has been increased!');
  218. }
  219. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  220. if (env('APP_ENV') == 'local') {
  221. dd($response);
  222. } else {
  223. abort(500);
  224. }
  225. } catch (HttpException $ex) {
  226. if (env('APP_ENV') == 'local') {
  227. echo $ex->statusCode;
  228. dd($ex->getMessage());
  229. } else {
  230. abort(422);
  231. }
  232. }
  233. }
  234. /**
  235. * @param Request $request
  236. */
  237. public function cancel(Request $request)
  238. {
  239. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  240. }
  241. /**
  242. * @return JsonResponse|mixed
  243. * @throws Exception
  244. */
  245. public function dataTable()
  246. {
  247. $query = Payment::with('user');
  248. return datatables($query)
  249. ->editColumn('user', function (Payment $payment) {
  250. return $payment->user->name;
  251. })
  252. ->editColumn('price', function (Payment $payment) {
  253. return $payment->formatToCurrency($payment->price);
  254. })
  255. ->editColumn('tax_value', function (Payment $payment) {
  256. return $payment->formatToCurrency($payment->tax_value);
  257. })
  258. ->editColumn('total_price', function (Payment $payment) {
  259. return $payment->formatToCurrency($payment->total_price);
  260. })
  261. ->editColumn('created_at', function (Payment $payment) {
  262. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  263. })
  264. ->make();
  265. }
  266. }