StripeRepository.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Shop\PaymentMethods\Stripe;
  3. use App\Shop\Checkout\CheckoutRepository;
  4. use App\Shop\Couriers\Courier;
  5. use App\Shop\Couriers\Repositories\CourierRepository;
  6. use App\Shop\Customers\Customer;
  7. use App\Shop\Customers\Repositories\CustomerRepository;
  8. use App\Shop\PaymentMethods\Stripe\Exceptions\StripeChargingErrorException;
  9. use Gloudemans\Shoppingcart\Facades\Cart;
  10. use Ramsey\Uuid\Uuid;
  11. use Stripe\Charge;
  12. class StripeRepository
  13. {
  14. /**
  15. * @var Customer
  16. */
  17. private $customer;
  18. /**
  19. * StripeRepository constructor.
  20. * @param Customer $customer
  21. */
  22. public function __construct(Customer $customer)
  23. {
  24. $this->customer = $customer;
  25. }
  26. /**
  27. * @param array $data Cart data
  28. * @param $total float Total items in the cart
  29. * @param $tax float The tax applied to the cart
  30. * @return Charge Stripe charge object
  31. * @throws StripeChargingErrorException
  32. */
  33. public function execute(array $data, $total, $tax) : Charge
  34. {
  35. try {
  36. $shipping = 0;
  37. $totalComputed = $total + $shipping;
  38. $customerRepo = new CustomerRepository($this->customer);
  39. $options['source'] = $data['stripeToken'];
  40. $options['currency'] = config('cart.currency');
  41. if ($charge = $customerRepo->charge($totalComputed, $options)) {
  42. $checkoutRepo = new CheckoutRepository;
  43. $checkoutRepo->buildCheckoutItems([
  44. 'reference' => Uuid::uuid4()->toString(),
  45. 'courier_id' => 1,
  46. 'customer_id' => $this->customer->id,
  47. 'address_id' => $data['billing_address'],
  48. 'order_status_id' => 1,
  49. 'payment' => strtolower(config('stripe.name')),
  50. 'discounts' => 0,
  51. 'total_products' => $total,
  52. 'total' => $totalComputed,
  53. 'total_paid' => $totalComputed,
  54. 'tax' => $tax
  55. ]);
  56. Cart::destroy();
  57. }
  58. return $charge;
  59. } catch (\Exception $e) {
  60. throw new StripeChargingErrorException($e);
  61. }
  62. }
  63. }