I'm following the Messagebird docs on sending an SMS through the messagebird API. When I run my app and go to the link in postman, I get no errors and "SUCCESS" is console.logged as well as the reponse. However I never recieve a text. When I go to the SMS logs on the messagebird dashboard there's nothing there except for the test SMS I sent rhough the messagebird dashboard
I've replaced my number for privacy purposes but there was no issue regarding the number being invalid
router.get("/testSMS", (req,res) => {
messagebird.messages.create({
originator : 'Movie App',
recipients : [ '123456778' ],
body : 'Hello World, I am a text message and I was hatched by Javascript code!'
}, function (err, response) {
if (err) {
console.log("ERROR:");
console.log(err);
} else {
console.log("SUCCESS:");
console.log(response);
}
});
})
Here's my console
This example works for me. If you add your number as a query param does this work for you?
router.get("/test/:phone", (req, res) => {
const { phone } = req.params;
// Ensure the phone nubmer follows the E.164 format (https://www.twilio.com/docs/glossary/what-e164)
if (!/^\+[1-9]{1}[0-9]{3,14}$/.test(phone)) {
return res.status(400).send("Invalid phone number");
}
// Sends a test SMS to the number specified in the request
messagebird.messages.create(
{
originator: "MessageBird",
recipients: [phone],
body: "This is a test message from MessageBird",
},
(err, response) => {
if (err) {
return res.send(err);
}
return res.send(response);
}
);
});
Related
I'm trying to send notifications based on business logic that runs (on nodejs) on my server via a cron.
Issue
Notifications aren't appearing on the device.
Description
I'm using the firebase admin node package.
My code looks something like this
import admin from "firebase-admin";
import serviceAccount from "../../firebase-admin.json" assert { type: 'json' };
import { getMessaging } from 'firebase-admin/messaging';
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
...
console.log(message);
await getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
My log output is something like this
{
notification: {
title: 'This is a string',
body: 'This is another string'
},
token: 'aLphaNumeric:reallyLongAlphaNumericWithDashesAndUnderscores'
}
Successfully sent message: projects/<project-name>/messages/<id>
Everything I'm seeing suggests this should be sent!
sendMulticast and the Admin FCM APIs allow you to multicast a message to a list of device registration tokens. You can specify up to 500 device registration tokens per invocation.
sendMulticast take 2 arguments as input, 1st one is notification which contains the title and body of the message.
The other argument is fcmTokens with type array, so you must pass that argument as array even though there is only one fcmToken
//Import the file where you have imported the service file.
const adminApp = require("../firebase/firebaseConfig");
const notificationToAll = (title, body, tokens) => {
var notibody = {
notification: {
title: title,
body: body,
},
tokens: tokens,
};
return new Promise((resolve, reject) => {
adminApp
.messaging()
.sendMulticast(notibody)
.then((response) => {
console.log(response.responses);
if (response.responses[0].error != undefined) {
console.log(JSON.stringify(response.responses[0].error));
}
resolve(response);
})
.catch((error) => {
console.log(JSON.stringify(error));
reject(error);
});
});
};
module.exports = notificationToAll;
app.js
const notificationToAll = require("./helper/notification");
notificationToAll(
"This is a string",
`This is another string`,
["aLphaNumeric:reallyLongAlphaNumericWithDashesAndUnderscores"]
)
This is tested code and working in a live environment.
so far I have been able to establish Test email delivery on strapi but I am not having any luck with posting a request when I am using the postman. For example I created route
// api/email/config/routes.json
{
"routes": [
{
"method": "POST",
"path": "/emails",
"handler": "Email.send",
"config": {
"policies": []
}
}
]
}
and then rest of the email body here is an example:
// File /api/email/controllers/Email.js
'use strict'
/**
* Read the documentation () to implement custom controller functions
*/
module.exports = {
/**
* Sends an email to the recipient in the body of the request
*/
send: async (ctx) => {
const body = ctx.request.body
const sendTo = body.email
strapi.log.debug(`Trying to send an email to ${sendTo}`)
try {
const emailOptions = {
to: sendTo,
subject: 'This is a test',
html: `<h1>Welcome!</h1><p>This is a test HTML email.</p>`,
}
await strapi.plugins['email'].services.email.send(emailOptions)
strapi.log.debug(`Email sent to ${sendTo}`)
ctx.send({ message: 'Email sent' })
} catch (err) {
strapi.log.error(`Error sending email to ${sendTo}`, err)
ctx.send({ error: 'Error sending email' })
console.log('====================================');
console.log(err);
console.log('====================================');
}
},
}
after running the application I posted request http://localhost:1337/emails and tried sending this json body {"email": "validemail#gmail.com"} but I keep receiving Method Not Allowed I can't seem to find what did I do wrong. Thank you in advance!
I tried to send OTP for email verification in my MERN stack project. I used the "two-step-auth" module to send OTP. It worked fine for 1 week. But suddenly OTP stopped being sent without showing any error.
OTP sending function:
async function sendOTP(emailId) {
try {
const res = await Auth(emailId);
console.log(res);
console.log(res.mail);
console.log(res.OTP);
console.log(res.success);
return String(res.OTP);
} catch (error) {
console.log(error);
return error;
}
}
when I call it outputs this :
{
status: 404,
mail: 'anikislampantha104#gmail.com',
success: false,
message: 'Unable to send mail'
}
If I print OTP by writing this
otp_sent.then((otp_s)=>{
console.log(otp_s);
})
otp_s shows undefined
But last one week it was working just fine
To start off, I do want to clarify that I know how to use APi's created in NodeJS in Angular. The problem I have is a little tricky.
I have a function that verifies the email used in registering:
exports.confirmEmail = function (req, res) {
ConfirmToken.findOne({
token: req.params.token
}, function (err, token) {
if (err) {
return res.status(500).send({
message: "Internal Server Error " + err
})
}
// token is not found into database i.e. token may have expired
if (!token) {
return res.status(400).send({
message: 'Your verification link may have expired. Please click on resend for verify your Email.'
});
}
// if token is found then check valid user
else {
Account.findOne({
_id: token._accountId,
email: req.params.email
}, function (err, user) {
if (err) {
return res.status(500).send({
message: "Internal Server Error " + err
})
}
// User does not exist
if (!user) {
return res.status(401).send({
message: 'The account does not exist'
});
}
// user is already verified
else if (user.isVerified) {
return res.status(200).send('User has been already verified. Please Login');
}
// verify user
else {
// change isVerified to true
user.isVerified = true;
user.save(function (err) {
// error occur
if (err) {
return res.status(500).send({
message: err.message
});
}
// account successfully verified
else {
return res.status(200).send('Your account has been successfully verified');
}
});
}
});
}
})
}
This is the response I get when I register an account
Now my question is: is there a way to pass in html code or have it show in a custom Angular component instead of displaying as simple plain text on the web browser as such
Your service should send a isVerified status back to the client. You are sending only a string at the moment
return res.status(200).send('Your account has been successfully verified');
based on this status, let's call it, isVerified your angular app would render a isVerfiedComponent.ts or notVerifiedComponent.ts
i am using graph api javascript example from here https://learn.microsoft.com/en-us/graph/api/user-list-joinedteams?view=graph-rest-beta&tabs=javascript
and my code is like:
async function(req, res) {
if (!req.isAuthenticated()) {
// Redirect unauthenticated requests to home page
res.redirect('/')
} else {
let params = {
active: { calendar: true }
};
// Get the access token
var accessToken;
try {
accessToken = await tokens.getAccessToken(req);
console.log("access token is:", accessToken)
} catch (err) {
req.flash('error_msg', {
message: 'Could not get access token. Try signing out and signing in again.',
debug: JSON.stringify(err)
});
}
if (accessToken && accessToken.length > 0) {
try {
console.log("vik testing stuff12 for teams")
const user = await graph.getTeams(accessToken)
console.log("graph me:::", user)
} catch (err) {
req.flash('error_msg', {
message: 'Could not fetch events',
debug: JSON.stringify(err)
});
}
} else {
req.flash('error_msg', 'Could not get an access token');
}
res.render('calendar', params);
}
}
getTeams is
getTeams: async function(accessToken) {
const client = getAuthenticatedClient(accessToken);
const events = await client
.api('/me/joinedTeams')
.version('beta')
.get();
return events;
}
this prints no results and no error. if I replace 'me/joinedTeams' to just 'me' then it returns logged in user details.
You can got a response successfully, so it seems no error with your code as you said if you call https://graph.microsoft.com/v1.0/me you can get user information.
And I tried to call this API using my account(my account hasn't joined any Teams), and got response like below, so if you got the same response as mine, perhaps you need to check if you have joined any Teams:
On the other hand, following the document, this API needs several permissions. So please obtain your access token when debug and use JWT tool to decrypt it to check if the access token have enough scope.
And I used the same request and got Teams information after adding my account to a team.