| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- <?php
- namespace Helpers;
- use Exception;
- use Location;
- use Stripe\Customer;
- use Stripe\Invoice;
- use Stripe\StripeClient;
- use Test;
- class StripeHelper {
- private StripeClient $client;
- public static function getInstance(): self {
- return new self(STRIPE_SECRET_KEY);
- }
- public function __construct(string $private_key) {
- $this->client = new StripeClient($private_key);
- }
- /**
- * @param Location $location
- * @return Customer
- * @throws Exception
- */
- public function createOrUpdateCustomer(Location $location): Customer {
- $customer = $location->getCustomer();
- $data = [
- "name" => $customer->name . " - " . $location->name,
- "email" => $location->email,
- "phone" => $location->phone,
- "metadata" => [
- "location_id" => $location->id,
- ]
- ];
- if($location->stripe_customer_id) {
- $stripe_customer = $this->client->customers->update($location->stripe_customer_id, $data);
- }
- else {
- $stripe_customer = $this->client->customers->create($data);
- }
- $location->stripe_customer_id = $stripe_customer->id;
- $location->commit();
- return $stripe_customer;
- }
- /**
- * @param Test $test
- * @param string $price
- * @return Invoice
- * @throws Exception
- */
- public function createInvoice(Test $test, string $price): Invoice {
- $location = $test->getLocation();
- if($location->stripe_customer_id) {
- $customer = $this->client->customers->retrieve($location->stripe_customer_id);
- }
- else {
- $customer = $this->createOrUpdateCustomer($location);
- }
- if($test->stripe_invoice_id) {
- return $this->client->invoices->retrieve($test->stripe_invoice_id);
- }
- $invoice = $this->client->invoices->create([
- "collection_method" => "send_invoice",
- "customer" => $customer->id,
- "metadata" => [
- "test_id" => $test->id,
- ],
- "days_until_due" => 0,
- "payment_settings" => [
- "payment_method_types" => [
- "card",
- ]
- ]
- ]);
- $this->client->invoiceItems->create([
- "customer" => $customer->id,
- "amount" => bcmul($price, 100),
- "currency" => "gbp",
- "description" => "Check Policy test fee",
- "metadata" => [
- "test_id" => $test->id,
- ],
- "invoice" => $invoice->id,
- ]);
- $this->client->invoices->finalizeInvoice($invoice->id);
- $test->stripe_invoice_id = $invoice->id;
- $test->commit();
- $this->client->invoices->sendInvoice($invoice->id);
- return $invoice;
- }
- }
|