I use AWS SES to send one-time passwords via email. I am implementing the same via SMS with AWS SNS.
I created a topic, otp
, and manually added the phone number to it as a subscription.
The following code works both locally and on the server:
var params = {
// TODO: fix this.
//PhoneNumber: "+351914...",
TopicArn: "arn:aws:sns:...:...:otp",
Message: "Your code is..."
}
var publish_text_promise = new AWS.SNS({apiVersion: '2010-03-31', profile_name: "sms"}).publish(params).promise();
// Handle promise's fulfilled/rejected states
publish_text_promise.then(
function(data) {
console.log("Message sent: %o", params);
console.log("MessageID is " + data.MessageId);
}).catch(
function(err) {
console.error("Error in sending OTP by SMS");
console.error(err, err.stack);
});
I would like to send directly to the phone number, so it does not require manual intervention and I can add other users on the same topic. When I add PhoneNumber
instead of TopicArn
, it sometimes works, and sometimes I get this message:
InvalidParameter: Invalid parameter: PhoneNumber Reason: +351914... is not valid to publish to
The phone number is correctly formatted: when I tested it locally, it always worked.
I have the same code locally and remotely and the same AWS credentials file as well.
Why does the code work locally and sometimes fail remotely? How can I send directly to phone numbers?
The issue was an invisible character in the phone number, which you can see after the 6:
InvalidParameter: Invalid parameter: PhoneNumber Reason: +3519...6 is not valid to publish to
I had cleaned the phone number before adding to Contacts on macOS, but it seems that Contacts adds these characters here and there. The character disappeared when I removed the phone number. Because the character was at the end, I missed it when I selected the phone number to copy-and-paste.
Following the comments, one solution to debug this issue is to try the AWS SNS console.
Therefore, this thread is closely related to this thread:
This was definitely caused by an encoding issue, paste the code below into jsfiddle, and mouseover to see the warning on the first plus sign which reads:
This character may get silently deleted by one or more browsers