| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- <?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 {
- if($location->legal_entity_name) {
- $name = sprintf("%s (%s)", $location->name, $location->legal_entity_name);
- }
- else {
- $name = $location->name;
- }
- $country = null;
- if($location->country === "United Kingdom") {
- $country = "GB";
- }
- $address = [
- "city" => $location->city,
- "country" => $country,
- "line1" => $location->address_1,
- "line2" => $location->address_2,
- "postal_code" => $location->postal_code,
- "state" => $location->county,
- ];
- $data = [
- "name" => $name,
- "email" => $location->email,
- "phone" => $location->phone,
- "address" => $address,
- "shipping" => null,
- "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();
- $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,
- "test_url" => sprintf("https://%s/account/tests/%d", DOMAIN, $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;
- }
- }
|