PHP Stripe retrieve paymentintent (connect) - javascript

I'm attempting to retrieve a paymentintent so i can validate that it's successful, when retrieving i always get a "no such payment intent" error.
Some relevant PHP code;
//setting api key
\Stripe\Stripe::setApiKey('sk_test_xxxxx');
//creating payment intent on pageload
$intent = \Stripe\PaymentIntent::create([
'amount' => 1099,
'currency' => 'USD',
'payment_method_types' => ['card'],
'application_fee_amount' => '500',
], [
'stripe_account' => 'acct_xxxx'
]);
//now on redirect(after coming back from 3DS with a $_GET that contains a intent id i'm retrieving paymentintent and confirming payment status.
$intent = \Stripe\PaymentIntent::retrieve($_GET['intentID'], array("stripe_account" => 'acct_xxxx'));
Relevant JS code on page
var stripe = Stripe('pk_test_xxxxx', {
stripeAccount: 'acct_xxxx'
});
stripe.handleCardPayment(clientSecret, {
payment_method_data: {
billing_details: {
name: cardHolder.value
},
card: {
"token": tokenResult["token"]["id"]
}
}
}).
//and more code which processes the redirect for 3ds.
var_dumping $intent will show that my error looks like this;
"error": {
"code": "resource_missing",
"doc_url": "https://stripe.com/docs/error-codes/resource-missing",
"message": "No such payment_intent: 'pi_xxxxx'",
"param": "intent",
"type": "invalid_request_error"
}

Related

Filter checkout session by metadata Stripe

I'm building a marketplace (you can imagine it like an Ebay where there are buyer and seller). And i want to get an items that bought customer (and vice versa with seller).
Here is my checkout session service:
async charge(userId: number, dto: CreateChargeDto) {
//Get an item by id
const item = await this.prisma.item.findUnique({
where: {
id: dto.itemId,
},
});
if (!item) {
throw new BadRequestException('There is no item with this id');
}
// Search for user
const user = await this.prisma.user.findUnique({
where: {
id: userId,
},
});
//update customer
await this.updateCustomer(user.stripeCustomerId, dto);
const session = await this.stripe.checkout.sessions.create({
success_url: 'http://localhost:3000/success?message=Succesful+payment',
cancel_url: 'http://localhost:3000/404?message=Payment+canceled',
mode: 'payment',
currency: 'pln',
customer: user.stripeCustomerId,
customer_update: {
address: 'auto',
},
metadata: {
seller_id: item.userId, // here is where i save seller id
},
line_items: [
{
quantity: 1,
price_data: {
currency: 'pln',
unit_amount: item.price * 100,
product_data: {
name: item.name,
images: item.images,
metadata: {
id: item.id,
},
},
},
},
],
});
return session.id;
}
async getCheckoutList(userId: number) {
const user = await this.prisma.user.findUnique({
where: {
id: userId,
},
});
const checkouts = await this.stripe.
return checkouts.data;
}
And now i wanna filter this session checkouts so i can display them in buyer (or seller) personal page.
const checkouts = await this.stripe.checkout.sessions.list({
where: {
metadata: {
seller_id: // seller id
}
}
How can i do it?
There's currently no way to filter for Checkout Sessions by metadata.
Some other options are :
Listen for the checkout.session.completed webhook event, save the data to your DB and then perform your own filtering. See https://stripe.com/docs/webhooks for more information on handling webhooks.
Add the metadata to the PaymentIntent also using the following parameter : https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-payment_intent_data-metadata. You can then use the Search API to filter for the
corresponding PaymentIntent with https://stripe.com/docs/search. Once
you have the PaymentIntent, retrieve the corresponding
Checkout Session with
https://stripe.com/docs/api/checkout/sessions/list#list_checkout_sessions-payment_intent
To filter for Checkout Sessions by Customer, you can use https://stripe.com/docs/api/checkout/sessions/list#list_checkout_sessions-customer
So the best in my opinion in this situation is to use a webhook.
The perfect example in Nestjs you can read here: https://wanago.io/2021/07/05/api-nestjs-stripe-events-webhooks/

Cannot charge a customer that has no active card

So I am getting the error in Stripe that "Cannot charge a customer that has no active cards".
I am using node js for this
Payment Code is given below
try {
const customer = await stripe.customers.create({
email: req.body.email,
source: req.body.id,
});
const payment = await stripe.charges.create(
{
amount: req.body.totalAmount * 100,
currency: "inr",
customer: customer.id,
receipt_email: req.body.email,
confirm: true,
off_session: true,
},
{
idempotencyKey: uuidv4(),
}
);
And I am getting the following error
type: 'StripeCardError',
raw: {
code: 'missing',
doc_url: 'https://stripe.com/docs/error-codes/missing',
message: 'Cannot charge a customer that has no active card',
param: 'card',
type: 'card_error',
}
Log out req.body.id as that might be null and then investigate why your frontend is not passing that parameter to your backend.
Second, confirm and off_session are not supported parameters on the /v1/charges endpoint.

Can't create subscriptions on Stripe

I can't create stripe subscription due to Missing required param: items.. I request it with items although.
The error:
{
"error": {
"code": "parameter_missing",
"doc_url": "https://stripe.com/docs/error-codes/parameter-missing",
"message": "Missing required param: items.",
"param": "items",
"type": "invalid_request_error"
}
}
The code:
const stripeCustomer = await stripe.customers.create({
name: name,
email: email,
plan: basicPlan,
})
const stripeSubscription = await stripe.subscriptions.create({
items: [{ plan: basicPlan }],
customer: stripeCustomer.id,
})
Stripe Customer account was successfully added.
Got the same problem. I've found out I'm lacking some package details

In Paypal, what protects the buyer that the correct amount will be charged to their account during checkout?

I am testing my code in PayPal sandbox using Braintree SDK.
I can set an amount in the client side e.g. 10 USD and the client can proceed with the checkout process.
But on the server side, after receiving the "nonce" code, I can charge the client 200 USD and there is no error or validation.
What protects the buyer from overpayment if the developer decides to charge more than what was said during checkout?
In the client side, I sent the intent option to "authorize", but I still can overcharge the buyer if I want to.
Client-side code
paypal.Button.render({
braintree: braintree,
client: {
sandbox: '{{$btClientToken}}'
},
env: 'sandbox',
commit: true,
payment: function (data, actions) {
return actions.braintree.create({
flow: 'checkout', // Required
intent:'authorize',
amount: '10', // Required
currency: 'USD', // Required
displayName: 'test dispaly name',
description: 'test description',
lineItems:[
{
quantity:'1',
unitAmount:'10',
totalAmount: '10',
name:'line item test',
description:'test description',
kind:'debit'
}
]
});
},
onAuthorize: function (payload) {
console.log(payload);
$.ajax({
method:'POST',
data:{
_token: '{{ csrf_token() }}',
payment_method_nonce: payload.nonce,
uid: '{{$uid}}',
order_id:payload.orderID,
payer_id:payload.payerID,
payment_token: payload.paymentToken
},
url:'{{url("cart/order/nonce")}}'
}).done((reply)=>{
console.log(reply);
});
},
}, '#paypal-pay');
Server-side code
$result = $gateway->transaction()->sale([
'amount' => '200.00',
'paymentMethodNonce' => $nonce,
'descriptor' => [
'name' => 'company name*myurl.com'
],
'options' => [
'submitForSettlement' => True,
"paypal" => [
"description" => $order->title
],
],
'lineItems' => [
[
'description' => 'TEST DESCRIPTION',
'name' => 'TEST NAME',
'quantity' => '1',
'unitAmount' => '200.00',
'totalAmount' => '200.00',
'kind' => 'debit'
]
]
]);
I get a successful transaction with 200 USD amount received in my seller dashboard.
Most consumer protection laws would allow the consumers to seek their money back from you if you incorrectly charged them, and if you did it systematically, a trading standards authority could take action against you.
PayPal themselves would also offer protection with the Buyer Protection guarantee, which would mean that the consumer could retrieve their money back directly from PayPal if the merchant didn’t give a refund themselves.
Edit
#Grumpy makes a good point that PayPal would most likely either block or ban your account after a few transactions.

SQLite PUT method not working due to SequelizeUniqueConstraintError

I built a PUT method for updating/editing inserted/existing records in sqlite db and when firing the put method the following error message is pulled up in the network tab for the PUT request. The issue seems to be related to SequelizeUniqueConstraintError and it auto-creating an id on update. Any thoughts or known workarounds?:
{
"error":"An error has occured trying to create the user.",
"err":{
"name":"SequelizeUniqueConstraintError",
"errors":[
{
"message":"id must be unique",
"type":"unique violation",
"path":"id",
"value":1,
"origin":"DB",
"instance":{
"id":1,
"email":"el#gmail.com",
"password":"$2a$08$HnRjfTzqsvwzobMQYM8bT.IkPbTSe6aOxy50l8/cUuuVhOgbl513.",
"firstName":"el",
"lastName":"leo",
"jobDescription":"test",
"gains":"100",
"costs":"50",
"balance":50,
"isAdmin":null,
"youAgree":null,
"createdAt":"2019-03-03T09:39:31.295Z",
"updatedAt":"2019-03-26T19:03:21.665Z"
},
"validatorKey":"not_unique",
"validatorName":null,
"validatorArgs":[
]
}
],
"fields":[
"id"
],
"parent":{
"errno":19,
"code":"SQLITE_CONSTRAINT",
"sql":"INSERT INTO `Users` (`id`,`email`,`password`,`firstName`,`lastName`,`jobDescription`,`gains`,`costs`,`balance`,`isAdmin`,`youAgree`,`createdAt`,`updatedAt`) VALUES (1,'el#gmail.com','$2a$08$HnRjfTzqsvwzobMQYM8bT.IkPbTSe6aOxy50l8/cUuuVhOgbl513.','el','leo','test','100','50',50,NULL,NULL,'2019-03-03 09:39:31.295 +00:00','2019-03-26 19:03:21.665 +00:00');"
},
"original":{
"errno":19,
"code":"SQLITE_CONSTRAINT",
"sql":"INSERT INTO `Users` (`id`,`email`,`password`,`firstName`,`lastName`,`jobDescription`,`gains`,`costs`,`balance`,`isAdmin`,`youAgree`,`createdAt`,`updatedAt`) VALUES (1,'el#gmail.com','$2a$08$HnRjfTzqsvwzobMQYM8bT.IkPbTSe6aOxy50l8/cUuuVhOgbl513.','el','leo','test','100','50',50,NULL,NULL,'2019-03-03 09:39:31.295 +00:00','2019-03-26 19:03:21.665 +00:00');"
},
"sql":"INSERT INTO `Users` (`id`,`email`,`password`,`firstName`,`lastName`,`jobDescription`,`gains`,`costs`,`balance`,`isAdmin`,`youAgree`,`createdAt`,`updatedAt`) VALUES (1,'el#gmail.com','$2a$08$HnRjfTzqsvwzobMQYM8bT.IkPbTSe6aOxy50l8/cUuuVhOgbl513.','el','leo','test','100','50',50,NULL,NULL,'2019-03-03 09:39:31.295 +00:00','2019-03-26 19:03:21.665 +00:00');"
}
}
This is the sample PUT method for reference:
put (user) { console.log('put user: ', JSON.stringify(user)) var userId = user.id console.log('put userId: ', userId) return Api().put(users/${user.id}, user) // return Api().put('users', userId, user) }

Categories