PaymentController.php 11 KB

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