PaymentController.php 11 KB

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