PaymentController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 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 LaravelDaily\Invoices\Classes\Party;
  20. use PayPalCheckoutSdk\Core\PayPalHttpClient;
  21. use PayPalCheckoutSdk\Core\ProductionEnvironment;
  22. use PayPalCheckoutSdk\Core\SandboxEnvironment;
  23. use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
  24. use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
  25. use PayPalHttp\HttpException;
  26. use LaravelDaily\Invoices\Invoice;
  27. use LaravelDaily\Invoices\Classes\Buyer;
  28. use LaravelDaily\Invoices\Classes\InvoiceItem;
  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. //payment notification
  171. $user->notify(new ConfirmPaymentNotification($payment));
  172. event(new UserUpdateCreditsEvent($user));
  173. //create invoice
  174. $seller = new Party([
  175. 'name' => 'Dennis L',
  176. 'phone' => '1234513',
  177. 'address' => 'Deutschlandstr 4, 66666 Hell',
  178. 'custom_fields' => [
  179. 'UST_ID' => '365#GG',
  180. ],
  181. ]);
  182. $customer = new Buyer([
  183. 'name' => 'Dennis Leipe',
  184. 'custom_fields' => [
  185. 'email' => 'dleipe@hafuga.de',
  186. 'order number' => '> 654321 <',
  187. ],
  188. ]);
  189. $item = (new InvoiceItem())->title($paypalProduct->description)->pricePerUnit($paypalProduct->price);
  190. $invoice = Invoice::make()
  191. ->buyer($customer)
  192. ->seller($seller)
  193. ->discountByPercent(0)
  194. ->taxRate(floatval($paypalProduct->getTaxPercent()))
  195. ->shipping(0)
  196. ->addItem($item)
  197. ->series('BIG')
  198. ->status(__('invoices::invoice.paid'))
  199. ->sequence(667)
  200. ->serialNumberFormat('{SEQUENCE}/{SERIES}')
  201. ->save('public');
  202. //redirect back to home
  203. return redirect()->route('home')->with('success', 'Your credit balance has been increased! Invoice: '.$invoice->url());
  204. }
  205. // If call returns body in response, you can get the deserialized version from the result attribute of the response
  206. if (env('APP_ENV') == 'local') {
  207. dd($response);
  208. } else {
  209. abort(500);
  210. }
  211. } catch (HttpException $ex) {
  212. if (env('APP_ENV') == 'local') {
  213. echo $ex->statusCode;
  214. dd($ex->getMessage());
  215. } else {
  216. abort(422);
  217. }
  218. }
  219. }
  220. /**
  221. * @param Request $request
  222. */
  223. public function cancel(Request $request)
  224. {
  225. return redirect()->route('store.index')->with('success', 'Payment was Canceled');
  226. }
  227. /**
  228. * @return JsonResponse|mixed
  229. * @throws Exception
  230. */
  231. public function dataTable()
  232. {
  233. $query = Payment::with('user');
  234. return datatables($query)
  235. ->editColumn('user', function (Payment $payment) {
  236. return $payment->user->name;
  237. })
  238. ->editColumn('price', function (Payment $payment) {
  239. return $payment->formatToCurrency($payment->price);
  240. })
  241. ->editColumn('tax_value', function (Payment $payment) {
  242. return $payment->formatToCurrency($payment->tax_value);
  243. })
  244. ->editColumn('total_price', function (Payment $payment) {
  245. return $payment->formatToCurrency($payment->total_price);
  246. })
  247. ->editColumn('created_at', function (Payment $payment) {
  248. return $payment->created_at ? $payment->created_at->diffForHumans() : '';
  249. })
  250. ->make();
  251. }
  252. }