stripe_helper.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. namespace Helpers;
  3. use Exception;
  4. use Location;
  5. use Stripe\Customer;
  6. use Stripe\Invoice;
  7. use Stripe\StripeClient;
  8. use Test;
  9. class StripeHelper {
  10. private StripeClient $client;
  11. public static function getInstance(): self {
  12. return new self(STRIPE_SECRET_KEY);
  13. }
  14. public function __construct(string $private_key) {
  15. $this->client = new StripeClient($private_key);
  16. }
  17. /**
  18. * @param Location $location
  19. * @return Customer
  20. * @throws Exception
  21. */
  22. public function createOrUpdateCustomer(Location $location): Customer {
  23. $customer = $location->getCustomer();
  24. $data = [
  25. "name" => $customer->name . " - " . $location->name,
  26. "email" => $location->email,
  27. "phone" => $location->phone,
  28. "metadata" => [
  29. "location_id" => $location->id,
  30. ]
  31. ];
  32. if($location->stripe_customer_id) {
  33. $stripe_customer = $this->client->customers->update($location->stripe_customer_id, $data);
  34. }
  35. else {
  36. $stripe_customer = $this->client->customers->create($data);
  37. }
  38. $location->stripe_customer_id = $stripe_customer->id;
  39. $location->commit();
  40. return $stripe_customer;
  41. }
  42. /**
  43. * @param Test $test
  44. * @param string $price
  45. * @return Invoice
  46. * @throws Exception
  47. */
  48. public function createInvoice(Test $test, string $price): Invoice {
  49. $location = $test->getLocation();
  50. if($location->stripe_customer_id) {
  51. $customer = $this->client->customers->retrieve($location->stripe_customer_id);
  52. }
  53. else {
  54. $customer = $this->createOrUpdateCustomer($location);
  55. }
  56. if($test->stripe_invoice_id) {
  57. return $this->client->invoices->retrieve($test->stripe_invoice_id);
  58. }
  59. $invoice = $this->client->invoices->create([
  60. "collection_method" => "send_invoice",
  61. "customer" => $customer->id,
  62. "metadata" => [
  63. "test_id" => $test->id,
  64. ],
  65. "days_until_due" => 0,
  66. "payment_settings" => [
  67. "payment_method_types" => [
  68. "card",
  69. ]
  70. ]
  71. ]);
  72. $this->client->invoiceItems->create([
  73. "customer" => $customer->id,
  74. "amount" => bcmul($price, 100),
  75. "currency" => "gbp",
  76. "description" => "Check Policy test fee",
  77. "metadata" => [
  78. "test_id" => $test->id,
  79. ],
  80. "invoice" => $invoice->id,
  81. ]);
  82. $this->client->invoices->finalizeInvoice($invoice->id);
  83. $test->stripe_invoice_id = $invoice->id;
  84. $test->commit();
  85. $this->client->invoices->sendInvoice($invoice->id);
  86. return $invoice;
  87. }
  88. }