How to create a stripe invoice without customer id - php

I'm trying to generate an invoice through stripe but the API requires a Client ID which I have no idea how to retrieve.
I'm using Session checkout:
method called by ajax
$checkout_session = Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'currency' => 'usd',
'unit_amount' => 2000,
'product_data' => [
'name' => 'Stubborn Attachments',
'images' => ["https://i.imgur.com/EHyR2nP.png"],
],
],
'quantity' => 1,
]],
'customer_email' => $email,
'mode' => 'payment',
'success_url' => $domain. '/success/{CHECKOUT_SESSION_ID}',
'cancel_url' => $domain. '/cancel/{CHECKOUT_SESSION_ID}',
]);
I receive
[
"id" => "cs_test_xxxxxxxxxxxxxxxx"
"object" => "checkout.session"
"allow_promotion_codes" => null
"amount_subtotal" => 2000
"amount_total" => 2000
"billing_address_collection" => null
"cancel_url" => "http://localhost/cancel/{CHECKOUT_SESSION_ID}"
"client_reference_id" => null
"currency" => "usd"
"customer" => null
"customer_details" => null
"customer_email" => "xxxxxxxxxxx#gmail.com"
"livemode" => false
"locale" => null
"metadata" => []
"mode" => "payment"
"payment_intent" => "pi_xxxxxxxxxxxxx"
"payment_method_options" => []
"payment_method_types" => array:1 [
0 => "card"
]
"payment_status" => "unpaid"
"setup_intent" => null
"shipping" => null
"shipping_address_collection" => null
"submit_type" => null
"subscription" => null
"success_url" => "http://localhost/success/{CHECKOUT_SESSION_ID}"
"total_details" => array:3 [
"amount_discount" => 0
"amount_shipping" => 0
"amount_tax" => 0
]
]
Create invoice requires a customer id which I don't have and have no idea where to get since session checkout creates a customer without giving me an id.

A Checkout Session in payment mode will generate a Payment Intent, not an Invoice. If you want to work solely with Invoices, you Checkout Session is not the right solution. If you don't care about Invoices and just want to be able to charge a customer for a one-off payment then you can continue using Checkout.
If you do want to work solely with Invoices, you need to do the following:
Create a Customer
Pass in the Customer ID when you create as many Invoice Items as you need
Pass in the Customer ID when you create an Invoice - this will automatically pull in any pending Invoice Items tied to the customer.
This is all summarized in this guide: https://stripe.com/docs/invoicing/integration

Related

Stripe Subscription Schedules Charge Instantly instead of waiting one hour

For some reason, when you create a "Subscription Schedules" stripe, it has very odd behavior where instead of trying to charge the customer, it keeps the invoice in draft for 1 hour and then closes the invoice and charges the customer.
I already have the card in the customer. I wonder if there is any way I can force the first phase of the subscription to be charged immediately.
My code:
$phases = [
[
'items' => [
[
'price_data' => [
'currency' => 'usd',
'product' => $product->stripe_product_id,
'recurring' => [
'interval' => $payment_plan['frequency'],
],
'unit_amount' => $payment_plan['stripe_amount']
],
'quantity' => 1,
],
],
'iterations' => (int) $payment_plan['total_payments']
],
];
$subscription = $stripe->subscriptionSchedules->create([
'customer' => $customer->stripe_customer_id,
'start_date' => 'now',
'end_behavior' => 'cancel',
'phases' => $phases,
]);
If you want to create a subscription immediately, you can do that without a Subscription Schedule and then set the schedule for that existing subscription:
https://stripe.com/docs/billing/subscriptions/subscription-schedules/use-cases#existing-subscription
Alternatively, if creating with the schedule like you're doing, once the subscription/invoice is created (as a draft) you can use the API to finalize it manually to proceed with the payment:
https://stripe.com/docs/api/invoices/finalize
Here is the solution:
$subscription = $stripe->subscriptionSchedules->create([
'customer' => $customer->stripe_customer_id,
'start_date' => 'now',
'end_behavior' => 'cancel',
'phases' => $phases,
]);
// now the invoice is a draft so we go get this invoice
$invoice = $stripe->invoices->all([
'limit' => 3,
'status' => 'draft',
'subscription' => $subscription->subscription,
'customer' => $customer->stripe_customer_id,
]);
//get the most recent draft
$invoice = $invoice->data[0];
//finalize the invoice (but this don't generate the payment for some reason)
$stripe->invoices->finalizeInvoice(
$invoice->id, [
'auto_advance' => true
]
);
//finaly pay the invoice
$invoice = $stripe->invoices->pay($invoice->id,[
'payment_method' => $token
]);

Stripe PHP Create customer and add subscription

The old way of doing this was as follows
$customer = \Stripe\Customer::create(array(
"description" => $domain,
"email" => $email,
"source" => $token,
"metadata" => array(
"name" => $name,
"phone" => $phone
),
));
$cus = $customer->id;
\Stripe\Subscription::create(array(
"customer" => $cus,
"plan" => "1",
));
But now I do not see the "PLAN" option on the subscription create. Here is what I have so far...
$customer = $stripe->customers->create([
'description' => 'Description text here nomadweb.design',
'name' => 'Sammy Malones',
'email' => 'name#email.com',
'phone' => '5124592222'
]);
$cus = $customer->id;
$stripe->subscriptions->create([
'customer' => $cus,
'plan' => '1'
]);
In the API Docs is says that it's required to use the items parameter.
My question is how to I add a subscription to a customer with the newer api?
This is their code but I don't understand
$stripe->subscriptions->create([
'customer' => 'cus_J34i3JonNQQXdO',
'items' => [
['price' => 'price_0IQyZLH7HxDXZRHqJfpwwqBB'],
],
]);
https://stripe.com/docs/api/subscriptions/create
In my stripe dashboard I have a product created which is a monthly subscription, it has an ID like prod_BlMuxdEQJSxfKJ So I'm guessing I need to pass that ID in somehow as an item?
I would encourage you to read about Prices, the successor to Plans, but you can also provide an existing Plan like plan_123 to the subscription creation request, and it will be converted to a Price for you:
$stripe->subscriptions->create([
'customer' => 'cus_123',
'items' => [
['price' => 'plan_123'],
],
]);
You can't provide a Product here directly, as Products are not directly tied to any amount or interval. You need to create Prices for those Products, either using the API or your Dashboard.
When creating a subscription, you can optionally define the recurring pricing ad-hoc, using price_data (API doc) and referencing the Product to be used:
$subscription = $stripe->subscriptions->create([
'customer' => 'cus_123',
'items' => [[
'price_data' => [
'unit_amount' => 5000,
'currency' => 'usd',
'product' => 'prod_456',
'recurring' => [
'interval' => 'month',
],
],
]],
]);
Thank you to Nolan, it looks like you need to grab the product pricing API ID which is provided in the dashboard.
Here is the updated code
$stripe->subscriptions->create([
'customer' => $cid,
'items' => [['price' => 'price_0IR0OGH7HxDXZRHq3sIg9biB'],],
]);
Here the price ID is attaching the product which is a subscription to the customer.
if you are using laravel and stripe php sdk with it then you can do it like this below:
\Stripe\Stripe::setApiKey(env('STRIPE_PRIVATE_KEY'));
// Use an existing Customer ID if this is a returning customer.
// $customer = \Stripe\Customer::create([
// "description" => $domain,
// "email" => $email,
// "source" => $token,
// "metadata" => [
// "name" => $name,
// "phone" => $phone
// ],
// ]);
$customer = \Stripe\Customer::create();
// $customer_id = $customer->id;
$Subscription = \Stripe\Subscription::create([
'customer' => $customer->id,
'items' => [[
'price' => $price_id,
]],
'payment_behavior' => 'default_incomplete',
'expand' => ['latest_invoice.payment_intent'],
]);
$ephemeralKey = \Stripe\EphemeralKey::create(
['customer' => $customer->id],
['stripe_version' => '2020-08-27']
);
// $paymentIntent = \Stripe\PaymentIntent::create([
// 'amount' => $amount,
// 'currency' => $currency,
// 'customer' => $customer->id
// ]);
$response = [
'request' => $data,
'paymentIntent' => $subscription->latest_invoice->payment_intent->client_secret,
'ephemeralKey' => $ephemeralKey->secret,
'customer' => $customer->id,
'subscriptionId' => $subscription->id,
];
return response($response, 200);
And then in your front end you can process the payment with the help of your paymentIntent secret.

Stripe API and ApplePay "Billing Address Invalid" issue

I am using this code to create Stripe checkout:
$checkout_session = \Stripe\Checkout\Session::create([
'customer_email' => 'my_test_email#gmail.com',
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'currency' => 'usd',
'unit_amount' => 1000,
'product_data' => [
'name' => 'Balance top-up',
],
],
'quantity' => 1,
]],
'mode' => 'payment',
'client_reference_id' => $clientReferenceId,
'success_url' => 'https://example.com/user-deposit/?result=success',
'cancel_url' => 'https://example.com/user-deposit/?result=failed',
'metadata' => [
'user_id' => '1',
],
]);
Everything works fine, but if I try to pay with ApplePay from the mobile browser - I got such an error (although everything is fine with this card and the billing address is filled in in the Apple account settings):
What should I do? In fact, I don't want to ask my users for the billing address, could I use some stored info (like country and city) to pass to this API request, or perhaps I could somehow force Stripe to do not ask for billing/shipping addresses (I do not sell goods, just for top-up an internal balance in my service)?

Specify Duration while creating Stripe Subscription Plan

I'm using Stripe PHP SDK to create a subscription plan dynamically.
use \Stripe\Plan;
Plan::create(array(
"amount" => 2000,
"interval" => "month",
"name" => "Amazing Gold Plan",
"currency" => "usd",
"id" => "gold")
);
I wanted to ask is there a way to mention/handle the duration of a plan. Like I wanted to make a subscription by the plan for a limited time suppose 3 months and after 3 months I wanted the plan to automatically get removed from the subscription. I don't want to cancel the whole subscription as in my case there could be multiple plans associated with a subscription. SO I simply want to remove/detach the plan from the subscription.
I had gone through the Stripe SDK docs to find this but to no avail.
A Subscription Schedule [1] will be what you require here to automate changes to the underlying Subscription using phases [2].
The use of a schedule will allow you to specify, for example, a monthly Price that will iterate for 3 months in the first phase. Then you can define in the next phase what will happen, for example change the Prices in some way, like adding or removing Prices. An example may look like this:
\Stripe\SubscriptionSchedule::create([
'customer' => 'cus_xxx',
'start_date' => 'now',
'end_behavior' => 'release',
'phases' => [
[
'items' => [
[
'price' => 'price_print', # Monthly Price
'quantity' => 1,
],
],
'iterations' => 3, # Iterates for 3 months
],
[
'items' => [
[
'price' => 'price_print',
'quantity' => 1,
],
[
'price' => 'price_digital', # An extra price
'quantity' => 1,
],
],
'iterations' => 1, # Iterate for 1 month
],
],
]);
[1] https://stripe.com/docs/billing/subscriptions/subscription-schedules#managing
[2] https://stripe.com/docs/api/subscription_schedules/object#subscription_schedule_object-phases
I believe you need to create price instead of plan and the code would be like this (Not sure I use different platform but you can try)
use \Stripe\Plan;
$price = \Stripe\Price::create([
'product' => '{{PRODUCT_ID}}',
'unit_amount' => 1000,
'currency' => 'usd',
'recurring' => [
'interval' => 'month',
'interval_count' => 2 //Try tweaking this value for change
],
]);

how to create multiple payments using PHP SDK Quickbooks

I am creating App for Quickbook in PHP
I am using https://github.com/intuit/QuickBooks-V3-PHP-SDK/
I want to make payments to multiple invoice in single API call.
I see their example but those make single payment. I need multiple payments towards various invoice for different customers.
How that is possible?
Their example code is here:
https://github.com/IntuitDeveloper/SampleApp-CRUD-PHP/blob/master/CRUD_Examples/Payment/PaymentCreate.php
So here's a snippet:
$theResourceObj = Payment::create([
"CustomerRef" =>
[
"value" => "1"
],
"TotalAmt" => 100.00,
"Line" => [
[
"Amount" => 100.00,
"LinkedTxn" => [
[
"TxnId" => "210",
"TxnType" => "Invoice"
]]
]]
]);
$resultingObj = $dataService->Add($theResourceObj);
Then if you refer to their documentation:
https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/payment#the-payment-object
You can see that the Line element is composed of Zero or more transactions accounting for this payment. including The invoice to which payment is applied. i.e. you can repeat things within Line, to apply the payment to more than one invoice.
So applying a payment to more than one invoice lists each individual invoice, and the amount of the payment to apply, in the repeating Line node array:
$theResourceObj = Payment::create([
"CustomerRef" =>
[
"value" => "1"
],
"TotalAmt" => 100.00,
"Line" => [
[
"Amount" => 50.00,
"LinkedTxn" => [
[
"TxnId" => "210",
"TxnType" => "Invoice"
]]
],
[
"Amount" => 25.00,
"LinkedTxn" => [
[
"TxnId" => "211",
"TxnType" => "Invoice"
]]
],
[
"Amount" => 25.00,
"LinkedTxn" => [
[
"TxnId" => "212",
"TxnType" => "Invoice"
]]
],
]
]);
$resultingObj = $dataService->Add($theResourceObj);
Finally I found solution for me.
API have Batch Option to add multiple Objects in single Batch.
Thanks to everyone

Categories