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
Related
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.
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"
}
I am working on a function to send emails to users, I already have my send mail function and it sends to a single user. I am trying to send to multiple users in an array now.
I am writing in Typescript and I am using mailgun as my email service provider
This is a sample send mail function:
const data = {
from: 'example#from.com',
to: 'example#reciever.com',
subject: 'Sample subject',
html: await email(), // I am getting the email template here
}
await mailgun.messages().send(data)
With the code above, I am sending email to a single user. The json below shows how I am receiving the list of emails:
[
{
"name": "User 1",
"email": "user1#gmail.com"
},
{
"name": "user 2",
"email": "user2#gmail.com"
}
]
I want to be able to send to multiple users and I want to do it the smart way. Please suggest the best solution with code if possible.
Thank you.
Assuming the send function is async and returns a promise:
async function sendMail(){
const myRecipients = [
{
"name": "User 1",
"email": "user1#gmail.com"
},
{
"name": "user 2",
"email": "user2#gmail.com"
}
]
const fromAddress = "my#email.address"
// map our recipient array to the message format expected by `send`
const myMessages = myRecipients.map(r => ({
from: fromAddress,
to: r.email,
subject: "somesubject",
html: "some html"
}))
// map our messages to a bunch of "in-flight" promises
const promises = myMessages.map(m => mailgun.messages().send(m))
// wait for all the promises to complete
await Promise.all(promises)
}
I assume you're using mailgun-js, which seems to have something called mailing list which you possibly could utilize. If not, then I would suggest that rather than simply iterating the users list and sending one email at the time (synchronously with await), trigger all emails to be sent asynchronously and then use Promise.all to know when all has been sent. Sample below is by no means tested (as i've never used mailgun) but it should give you an idea on how to implement it.
const users = [
{
"name": "User 1",
"email": "user1#gmail.com"
},
{
"name": "user 2",
"email": "user2#gmail.com"
}
];
const sendEmailToUser = async (user) => {
const data = {
from: 'example#from.com',
to: 'example#reciever.com',
subject: 'Sample subject',
html: 'await email()'
};
await mailgun.messages().send(data);
};
(async () => {
const sendEmailPromises = [];
for(const user of users) {
// Start sending all emails
sendEmailPromises.push(sendEmailToUser(user));
}
// Wait for all emails to be sent
await Promise.all(sendEmailPromises);
// Do something
})()
You will have to iterate the data structure anyway.
var users = [
{
"name": "User 1",
"email": "user1#gmail.com"
},
{
"name": "user 2",
"email": "user2#gmail.com"
}
];
users.forEach(function(user){
name = user.name;
email = user.email;
var data = {
from: 'example#from.com',
to: email,
subject: 'Sample subject',
html: await email(),
}
await mailgun.messages().send(data);
});
use a array map
i dont know about typescript.
you can get all elements like this
for ES6
user_list.map(user => console.log(user.name, user.email))
I'm building an app in Node and I'm using mandrill to send emails every time there is a new user to a predefined array of emails. I have an array of emails:
And I have this function where
newUserEmail(user_name, email) {
emailArray = [example1#ex.com, example2#ex.com, example3#ex.com]
const message = {
html: '<p>Name: *|NAME|* <br> Email: *|EMAIL|*</p>',
text: 'Name: *|NAME|*, Email: *|EMAIL|*',
subject: 'New person arrived',
from_email: 'newperson#example.com',
from_name: 'New',
to: [{
email: emailArray,
type: 'to'
}],
merge: true,
merge_vars: [{
rcpt: emailArray,
vars: [{
name: 'NAME',
content: user_name
}, {
email: 'EMAIL',
content: email
}]
}]
};
mandrill_client.messages.send({ message }, function(result) {
console.log(result);
}, function(e) {
console.log(`A mandrill error occurred: ${e.name} - ${e.message}`);
});
}
I get this on my console:
[ { email: 'Array',
status: 'invalid',
_id: '...',
reject_reason: null } ]
If I set only one email, it gets sent without problems.
Do I need to make a loop and run this function as many times as there are emails in the array? I hoped mandrill would recognise emails in the array :(
From what I gathered after a look at the documentation it looks like each object in the "to" array is an individual email address.
I would not run the function for each email address. Just map over the email array.
For example:
const formattedArray = emailArray.map(email => ({ email, type: 'to' }));
// if you're not a fan of arrow functions
const formattedArray = emailArray.map(function(email) {
return { email, type: 'to' };
});
Then in the mandrill message you can just set "to" equal to the formattedArray
to: formattedArray
I am having a problem with the user model that I'm using with Mongoose and MongoDB to create each profile in my database. It works fine to post one user, but throws the following error if I logout and try again:
{
"name": "MongoError",
"message": "E11000 duplicate key error collection: CourtAPIDev.users index: trackers.case_id_1 dup key: { : null }",
"driver": true,
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error collection: CourtAPIDev.users index: trackers.case_id_1 dup key: { : null }"
}
According to mongoose documentation: If there is more than one document (a second user) without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error. I don't know how to set this _id property for the trackers property –– I thought it generated automatically!
Here's the trackers part of my Schema. And the relevant case_id property, which seems to be throwing the "null" error.
The whole repository can be found on my Github here, but the likely problem spots are the ones I highlighted, I think. Here's the github link: https://github.com/KingOfCramers/node_login_with_trackers
user model:
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
trim: true,
minLength: 1,
unique: true,
validate: {
validator: (value) => {
return validator.isEmail(value);
},
message: '{VALUE} is not a valid email'
}
},
password: {
type: String,
required: true,
minlength: 6
},
tokens: [{
access: {
type: String,
required: true
},
token: {
type: String,
required: true
}
}],
trackers: {
tweets: [TwitterSchema],
legislation: [LegislationSchema],
court_cases: [CourtCaseSchema]
},
frequency: [EmailSchema]
});
Express route:
app.post("/users", (req,res) => {
var body = _.pick(req.body, ['email', 'password']);
body.frequency = {
alert_time: new Date(),
email: req.body.email
}
var user = new User(body);
user.save().then(() => {
return user.generateAuthToken();
}).then((token) => {
res.header("x-auth", token);
res.send(user);
}).catch((e) => {
res.status(400).send(e);
});
});
Test (mocha):
it("Should post a new user", (done) => {
var email = "uniqueemail#example.com"
var password = "9webipasd"
supertest(app)
.post("/users") // Post request to the /todos URL
.send({
email,
password
})
.expect(200)
.expect((res) => {
expect(res.headers).toIncludeKey('x-auth')
expect(res.body._id).toExist();
expect(res.body.email).toBe(email);
})
.end((err) => {
if(err){
return done(err);
}
User.findOne({email}).then((user) => {
expect(user).toExist();
expect(user.password).toNotBe(password);
done();
}).catch((e) => done(e));
});
});
My guess is that there is an index on CourtCaseSchema.case_id which does not allow duplicates.
I think you could check (in a mongo shell) that with CourtAPIDev.court_cases.getIndexes() (I think your db is named CourtAPIDev and the collection is named court_cases but I am not sure about that).
Also if you clean the test db after each run, that would explain why the tests are passing, since there is no more than one user.
Turns out, it was to do with my mongodb database, not any of my code. After searching around online, I found that if I logged into the mongo shell and then dropped all indexes from the users collection, it solved my problem. Could someone explain why this was causing my program to crash? I think it may have to do with an old user model, but I don't really understand. Thanks!
Even if you have all of your keys as unique=False, you may still get E11000 duplicate key error. So in that case, just follow these steps and check if your error is resolved.
Delete all documents from the collection (e.g. db.collection_name.deleteMany({}))
Drop the COLLECTION (NOT THE DATABASE) (e.g db.collection_name.drop())
Cheers !!