Create an invoice for stripe payments - php

I'm using Stripe for one-time payments and subscriptions.
To create a payment, I use Stripe Checkout:
\Stripe\Checkout\Session::create([
'customer' => 'cus_XXXXX',
'success_url' => '',
'cancel_url' => '',
'payment_method_types' => ['card'],
'mode' => ($isSubscription ? 'subscription' : 'payment'),
'line_items' => [...]
]);
header('Location: '.$checkout_session->url);
exit;
This code automatically create an invoice for subscription mode but not for one-time payments.
I've tried this to create a new invoice but how can I do to make it related to previous payment, closed and paid?
$stripe = new Stripe\StripeClient('xxx');
$stripe->invoiceItems->create([
'customer' => 'cus_XXXXX',
'amount' => '1000',
'currency' => 'eur',
'description' => 'Lorem ipsum...'
]);
$invoice = $stripe->invoices->create([
'customer' => 'cus_XXXXX',
]);

I found a way to create an invoice for each payment mark paid.
This, however, doesn't link them to a payment.
On the webhook checkout.session.completed do the following:
$stripe = new Stripe\StripeClient('xxx');
// Create invoice lines
$stripe->invoiceItems->create([
'customer' => 'cus_XXXXX',
'amount' => '1000',
'currency' => 'eur',
'description' => 'Lorem ipsum...'
]);
// Create invoice
$invoice = $stripe->invoices->create([
'customer' => 'cus_XXXXX',
]);
// Finalize and mark invoice paid outside of Stripe
$invoice->finalizeInvoice();
$invoice->pay(['paid_out_of_band' => true]);

I believe you are looking for this: https://stripe.com/docs/payments/checkout/post-payment-invoices
To enable invoice creation, set invoice_creation[enabled] to true when
creating a Checkout session.

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.

Can you pass a shipping address to Stripe Checkout

I am using Stripe Checkout API to direct a website user to make payment.
Is there a way to pass a shipping address to the hosted checkout page so it's gathered from the referrer rather then Stripe themselves?
function createSession()
{
require 'vendor/autoload.php';
\Stripe\Stripe::setApiKey('[API_KEY_REDACTED]');
$YOUR_DOMAIN = '[SITE_URL_REDACTED]';
// Calculate price
$price = 50;
$checkout_session = \Stripe\Checkout\Session::create([
'billing_address_collection' => 'required',
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'currency' => 'gbp',
'unit_amount' => $price,
'product_data' => [
'name' => 'Product'
],
],
'quantity' => 1,
]],
'mode' => 'payment',
'success_url' => $YOUR_DOMAIN . '/success',
'cancel_url' => $YOUR_DOMAIN . '/cancel',
]);
return json_encode(['id' => $checkout_session->id]);
}
You can add the following line to make Stripe ask for a shipping address, but I want to pass this from the referrer instead.
'shipping_address_collection' => [
'allowed_countries' => ['US', 'CA'],
],
To do this you would create a Customer and provide their shipping address, then provide that existing Customer when creating the Checkout session:
$checkout_session = \Stripe\Checkout\Session::create([
'customer' => 'cus_123',
...
]);

Paypal Checkout SDK - immediate payment

I need to use Paypal checkout in order to accept immediate payment on my Laravel website, and I switched from old Paypal PHP SDK to the new Paypal checkout SDK to support API V2.
I followed the samples codes that provided in the new SDK, I have to create all workflow on my server, so I created an order with intent=CAPTURE with other required fields.
$request = new OrdersCreateRequest();
$request->headers["prefer"] = "return=representation";
$request->body = $this->buildMinimumRequestBody(...);
$response = $this->client->execute($request);
// redirect the user to approval link.
Order body:
return array(
'intent' => 'CAPTURE',
'application_context' =>
array(
'return_url' => 'https://example.com/return',
'cancel_url' => 'https://example.com/cancel',
'locale' => 'en-US',
'user_action' => 'PAY_NOW',
'shipping_preference'=> 'NO_SHIPPING'
),
'purchase_units' =>
array(
0 =>
array(
'amount' =>
array(
'currency_code' => 'USD',
'value' => 12,
'breakdown' =>
array(
'item_total' =>
array(
'currency_code' => 'USD',
'value' => 10,
),
'tax_total' =>
array(
'currency_code' => 'USD',
'value' => 2,
),
),
),
),
),
);
After the user redirected to approval URL and approving it, I execute the payment like below:
$response = $this->client->execute(new OrdersCaptureRequest($payment_id));
Below is the response after executing the payment.
Order and Payment response
So after directing the user to the approval page, then after approving the payment, then executing the order, I got the above result in the attached screenshot which shows the Order status is completed but the payment status is still "pending" and the reason is "PENDING_REVIEW", so I would like to ask if there is any error or something missed to make the payment immediately without waiting for review with an example.
Thanks.

Stripe saying 'Payment not completed' Stripe connect php

When transferring money to a connected account on Stripe using this code
// // Create a PaymentIntent:
$method = \Stripe\PaymentMethod::create([
'type' => 'card',
'card' => [
'number' => '4242424242424242',
'exp_month' => 12,
'exp_year' => 2020,
'cvc' => '314',
],
]);
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => $AMOUNT1,
'currency' => 'nzd',
'payment_method_types' => ['card'],
'payment_method' => $method->id,
'customer' => CUSTOMER_ID,
'transfer_group' => '{ORDER'.$_SESSION['order_id'].'}',
]);
// Create a Transfer to a connected account (later):
$transfer = \Stripe\Transfer::create([
'amount' => $AMOUNT2,
'currency' => 'nzd',
'destination' => $ACC_ID,
'transfer_group' => '{ORDER'.$_SESSION['order_id'].'}',
]);
The payment stores on the connected account's dashboard and says its completed but when it stores on my Payments tab it says that the payment is incomplete and that the buyer has not completed the payment
Prev1
Prev2
You need to confirm the payment intent, either by providing confirm=true at creation or by making a call to /confirm.
You're creating a transfer from your account to the connected one, which succeeds, and a payment that you never complete.

Categories