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; } }