PaymentController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 LaravelDaily\Invoices\Classes\Party;
  21. use PayPalCheckoutSdk\Core\PayPalHttpClient;
  22. use PayPalCheckoutSdk\Core\ProductionEnvironment;
  23. use PayPalCheckoutSdk\Core\SandboxEnvironment;
  24. use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
  25. use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
  26. use PayPalHttp\HttpException;
  27. use LaravelDaily\Invoices\Invoice;
  28. use LaravelDaily\Invoices\Classes\Buyer;
  29. use LaravelDaily\Invoices\Classes\InvoiceItem;
  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. //payment notification
  172. $user->notify(new ConfirmPaymentNotification($payment));
  173. event(new UserUpdateCreditsEvent($user));
  174. //create invoice
  175. $seller = new Party([
  176. 'name' => 'Hafuga Company',
  177. 'phone' => '+49 12346709',
  178. 'address' => 'Deutschlandstr 4, 66666 Hell',
  179. 'custom_fields' => [
  180. 'UST_ID' => '365#GG',
  181. 'E-Mail' => 'invoice@hafuga.de',
  182. ],
  183. ]);
  184. $customer = new Buyer([
  185. 'name' => 'Not Dennis',
  186. 'custom_fields' => [
  187. 'email' => 'customer@google.de',
  188. 'order number' => '> 654321 <',
  189. ],
  190. ]);
  191. $item = (new InvoiceItem())->title($paypalProduct->description)->pricePerUnit($paypalProduct->price);
  192. $lastInvoiceID = \App\Models\invoice::where("invoice_name","like","%".now()->format('M')."%")->max("id");
  193. $newInvoiceID = $lastInvoiceID + 1;
  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('M'))
  203. ->delimiter("-")
  204. ->sequence($newInvoiceID)
  205. ->serialNumberFormat('{SEQUENCE} - {SERIES}')
  206. ->logo(public_path('vendor/invoices/logo.png'))
  207. ->save('public');
  208. $user->notify(new InvoiceNotification($invoice));
  209. \App\Models\invoice::create([
  210. 'invoice_user' => $user->id,
  211. 'invoice_name' => "invoice_".$invoice->series.$invoice->delimiter.$invoice->sequence,
  212. 'payment_id' => $payment->payment_id,
  213. ]);
  214. //redirect back to home
  215. return redirect()->route('home')->with('success', 'Your credit balance has been increased! Find the invoice in your Notifications');
  216. }
  217. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  218. if (env('APP_ENV') == 'local') {
  219. dd($response);
  220. } else {
  221. abort(500);
  222. }
  223. } catch (HttpException $ex) {
  224. if (env('APP_ENV') == 'local') {
  225. echo $ex->statusCode;
  226. dd($ex->getMessage());
  227. } else {
  228. abort(422);
  229. }
  230. }
  231. }
  232. /**
  233. * @param Request $request
  234. */
  235. public function cancel(Request $request)
  236. {
  237. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  238. }
  239. /**
  240. * @return JsonResponse|mixed
  241. * @throws Exception
  242. */
  243. public function dataTable()
  244. {
  245. $query = Payment::with('user');
  246. return datatables($query)
  247. ->editColumn('user', function (Payment $payment) {
  248. return $payment->user->name;
  249. })
  250. ->editColumn('price', function (Payment $payment) {
  251. return $payment->formatToCurrency($payment->price);
  252. })
  253. ->editColumn('tax_value', function (Payment $payment) {
  254. return $payment->formatToCurrency($payment->tax_value);
  255. })
  256. ->editColumn('total_price', function (Payment $payment) {
  257. return $payment->formatToCurrency($payment->total_price);
  258. })
  259. ->editColumn('created_at', function (Payment $payment) {
  260. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  261. })
  262. ->make();
  263. }
  264. }