Stripe Create Invoice and auto charge - php

I am creating an invoice and auto charging a customer via their PHP package. The issue is though the invoice is created but the card on file is not charged, it says fail. This is odd to me because if I go into the dashboard online, find the invoice the is listed as "failed" and manually click the "retry charge" it works. Why would this be? Its clearly creating the invoice correctly and trying to charge the card on file but the card seems to only clear on ALL of these invoices if I go in and manually retry the charge.
$stripe = new \Stripe\StripeClient(config('XXXXXXXXXXXXXXXXX'));
$item = $stripe->invoiceItems->create([
'customer' => $subscription->stripe_customer,
'amount' => $total,
'currency' => 'usd',
'description' => 'Erro Coffee Subscription ' . $subscription_type->bags
]);
$invoice = $stripe->invoices->create([
'customer' => $subscription->stripe_customer,
'collection_method' => 'charge_automatically',
'auto_advance' => true,
"metadata" => [
"order_type" => "subscription",
"subscription_refill" => "true",
"subscription_id" => $subscription->id
]
]);

Related

Stripe : No card attached to customer after a checkout session payment

I'm using Stripe with PHP, I want to create subscription to customer after a payment made with Stripe Checkout Session.
But, the problem is that when we do a one shot payment with Stripe Checkout Session, Stripe does not attach the source (Credit card) to the customer, and when I try to subscribe this customer to a plan, Stripe return me the error :
This customer has no attached payment source or default payment method.
I don't understand why Stripe don't attach the card to the customer with one shot payment because Stripe do it when we use a Checkout Session with Subscription.
How I create checkout session :
$checkout_session = Session::create([
'payment_method_types' => ['card'],
'mode' => 'payment',
'customer' => 'cus_xxxxxxxx',
'line_items' => [[
'price' => 'price_xxxxx', // Oneshot payment
'quantity' => 1,
]]
]);
How I try to subscribe customer (After successful payment) :
$subscription = Subscription::create([
'customer' => 'cus_xxxxxxxx',
'items' => [
['price' => 'price_XXXXXXX'] // Recurrent payment
],
'trial_from_plan' => true,
]);
Thank you for your help
When accepting a one-time payment with Checkout, it won't create a Customer or save card details by default. What you have to do is configure Checkout to do this for you during the payment. This is covered in their documentation here.
What you need to do is set the payment_intent_data[setup_future_usage] parameter like this:
$checkout_session = Session::create([
'payment_method_types' => ['card'],
'mode' => 'payment',
'customer' => 'cus_xxxxxxxx',
'line_items' => [[
'price' => 'price_xxxxx', // Oneshot payment
'quantity' => 1,
]],
'payment_intent_data' => [
'setup_future_usage' => 'off_session',
]
]);
After that, you will have a Customer cus_123 and a PaymentMethod pm_123 that you can re-use. That PaymentMethod will not be the default one though so you need to make sure that you pass its id in the default_payment_method parameter when you create the Subscription like this:
$subscription = Subscription::create([
'customer' => 'cus_xxxxxxxx',
'items' => [
['price' => 'price_XXXXXXX'] // Recurrent payment
],
'trial_from_plan' => true,
'default_payment_method' => 'pm_12345',
]);
Also note that you can start a Subscription directly from Checkout as documented here.

Stripe - create invoice items and send invoice via e-mail to connected account

I create invoice item for every worker against job.
$product= $stripe->products->create(['name' => $job->name]);
$price = $stripe->prices->create([
'product' => $product['id'],
'unit_amount' => $amount,
'currency' => 'gbp',
]);
$items = $stripe->invoiceItems->create([
'customer' => $user->customer_id,
'price'=>$price['id']
]);
i need to send invoice on specific date.
when company pay invoice automatically transfer to connected account for every invoice items.
but its send to all invoice items in invoice to one connected account
$invoice = \Stripe\Invoice::create([
'customer' => $customer_id,
'application_fee_amount' => 10,
], ['stripe_account' => '{{CONNECTED_ACCOUNT_ID}}']);
$response= $stripe->invoices->sendInvoice($inovice['id'],[]);

Stripe sca subscription php and charge automatically

I have implemented the Stripe SCA migration
my serve side code to create payment intent is as follows
$intent = \Stripe\PaymentIntent::create([
'payment_method' => $requestData['payment_method_id'],
'amount' => $requestData->amount,
'currency' => $requestData->currencyIso,
'payment_method_types' => ['card'],
'confirmation_method' => "manual",
'confirm' => true,
'setup_future_usage'=>"off_session",
]);
return $intent;
And my js code is as below to create card payment and handle response
stripe.createPaymentMethod('card', cardElement, {
billing_details: {name: cardholderName.value}
})
and handle the response:
function handleServerResponse(response) {
if (response.error) {
} else if (response.requires_action) {
stripe.handleCardAction(
response.payment_intent_client_secret
).then(function(result) {
if (result.error) {
} else {
// The card action has been handled
// The PaymentIntent can be confirmed again on the server
fetch('https://test.com/server.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
payment_method_id: result.paymentMethod.id,
amount: amount
})
}).then(function(confirmResult) {
console.log(confirmResult);
return confirmResult.json();
}).then(handleServerResponse);
}
});
}
}
}
$plan = Plan::create([
'currency' => $currency,
'interval' => 'month',
'product' => $product->id,
'nickname' => 'Payment Plan for order - ' . $order_id,
'amount' => $price,
'metadata' => [
'order_number' => $order_id,
'bgt_customer_number' => $customer_id,
],
]);
$schedule = SubscriptionSchedule::create([
'customer' => $customer->id,
'start_date' => 'now',
'end_behavior' => 'cancel',
'metadata' => [
'local_id' => $order_id,
'local_account_id' => $account_id,
'local_currency_id' => $currency_id,
'local_user_id'=> $user_id,
'local_installments_total' => $plan_length,
'bgt_customer_number' => $customer_id,
'order_number' => $order_id,
'invoice_description' => 'Payment Plan for order - ' . $order_id
],
'phases' => [
[
'items' => [
[
'plan' => $plan->id,
],
],
'collection_method'=> 'charge_automatically',
'iterations'=>$plan_length
],
],
]);
$metadata = [
'installments_paid' => '0',
'installments_total' => $plan_length,
'local_id' =>$order_id,
'local_account_id' =>$account_id,
'local_currency_id' =>$currency_id,
'subscription_schedule_id' => $schedule->id
];
$subscription_id=$schedule->subscription;
$result=Subscription::update($subscription_id,
[
'metadata' => $metadata,
'default_payment_method' => $paymentMethodParams['payment_method'],
'proration_behavior' =>'always_invoice',
//Create only after adding payment method id in customer
]
);
I am getting the SCA modal for sca cards and workflow is correct.
But what concerns me is testing the subscription created using sca
I tested using 4000000000003220 amd also 424242424242424.. and subscription is created with 3 installments.
The subscription is created with correct installments:
But what concerns me is the subscription first installment is not being charged immediately.
Invoice shows as:
This draft invoice was generated by a subscription. It can be edited
until it's automatically finalized in 1 hour.
.
When I try to complete the charge from stripe dashboard (as a part of test) it shows
The invoice was finalized, but the customer needs to complete 3D
Secure authentication for the payment to succeed. This additional
step is required by their bank to prevent fraud. 3D Secure emails are
disabled in your settings, so you'll need to notify the customer
manually
The invoice failed to capture.
Question:
1: I wanted the first installment or schedule to happen.
How do I accomplish this in staging env. Am I missing any points here in creating subscription or SCA methods?
2: What is really 'confirmation_method' => "manual". Really confused.
When using Stripe Subscriptions you typically won't be creating Payment Intents yourself. Instead you'll be creating and interacting with Billing objects like Subscriptions and Invoices. The Invoices will create the Payment Intents for you. Stripe has a guide that walks you through taking payment information and creating a Subscription. If you read through and follow that guide you should be able to build what you want.
To answer your specific questions:
Question: 1: I wanted the first installment or schedule to happen. How do I accomplish this in staging env. Am I missing any points here in creating subscription or SCA methods?
This is likely because you're creating a Payment Intent and paying that which is unrelated to the Payment Intent belonging to the Invoice of your Subscription.
2: What is really 'confirmation_method' => "manual". Really confused.
The confirmation_method property controls how a Payment Intent can be confirmed. However, if you're using Subscriptions and want to support SCA you should ignore this property and instead follow the guide linked above.

stripe charge with existing consumer

I use this code to make a payment and create a new customer on my stripe dashboard.
$customer = \Stripe\Customer::create([
"name" => $utente,
"source" => $_POST['stripeToken'],
"email" => $row['mail'],
]);
$charge = \Stripe\Charge::create([
"customer" => $customer->id,
"amount" => $amount_cents,
"currency" => "eur",
"description" => $description
]);
The information such as the name or email the use to create a new customer, are taken from the dashboard of my site when a user is registered and connected to it.
This concern the user's first payment .php file.
on the second user's payment, the site redirect to a second .php file, where I need to add a second payment to the customer previously created. the problem is that if I keep the same code, on the stripe dashboard I find myself two equal customers. I don't know how to get the customer id when, when I redirect to the second payment page, as user information I only have the mail and the name .. how can I do?
I'll try something like that by searching on stripe api reference:
$customer = \Stripe\Customer::all([
'email' => $row['mail']
]);
$charge = \Stripe\Charge::create([
"customer" => $customer['data']->id,
"amount" => $amount_cents,
"currency" => "eur",
"description" => $description
]);
but it give me the error
Must provide source or customer..
Listing customers will return an object with a data property. data is a list of customers so you'll need to index into that list and grab one of the customers before looking at their ID. It should look something like:
$customer = \Stripe\Customer::all([
'email' => $row['mail']
]);
$charge = \Stripe\Charge::create([
'customer' => $customer->data[0]->id,
'amount' => $amount_cents,
'currency' => 'eur',
'description' => $description
]);

Braintree marketplace - What happens if Master Merchant do charge client at time time of sale, but has to pay to submerchant

I have implemented PHP braintree API in a project, I want to use Marketplace api for the same.
Now, we have promotional events and we do not charge client, but we have to pay amount to sub-merchant who has delivered goods.
So below is the code to add service fees, which is clear that at the time of sale we have to add sub-merchant id for merchantAccountId, amount will be payment charged from client, what is paymentMethodNonce?
$result = Braintree_Transaction::sale(array(
'merchantAccountId' => 'provider_sub_merchant_account',
'amount' => '10.00',
'paymentMethodNonce' => 'nonce-from-the-client',
'serviceFeeAmount' => "1.00"
));
Another query is, at the time of sale we have to pass credit card details of the client? What if client is already in vault ?
Below is another code from Braintree document with creditCard details
$result = Braintree_Transaction::sale(
array(
'amount' => "100",
'merchantAccountId' => "blue_ladders_store",
'creditCard' => array(
'number' => "4111111111111111",
'expirationDate' => "12/20",
),
'options' => array(
'submitForSettlement' => true,
'holdInEscrow' => true,
),
'serviceFeeAmount' => "10.00"
)
);
If we do not add creditCard number and have to pay sub-merchant then how can that be done.
Thanks

Categories