Can you check if a Phone Number is a verified caller ID through the twilio-client? - node.js

I need a Twilio expert to answer a question for me if they can. I have an application I'm developing in which we want a user to be able to enter a phone number and call someone with a selected phone number as the caller ID. Trick is that caller ID must be in our account Verified Caller IDs list. Now I have found several examples and tutorials about how to do this using the Twilio SDK, however we're using that on our back-end where all our tokens are stored and Twilio-Client on the front-end. Does anyone know of a way to verify a callerID using the Twilio-Client device on the front-end? Big thanks in advance.

Twilio developer evangelist here.
The Twilio Client JS SDK is mostly concerned with placing calls using WebRTC. It does not include features for calling the regular API, including the verified caller id list.
You could do a couple of things here.
Either, before you place the call, make an ajax request to your own server and make a check there against your verified caller IDs.
Or, when the call is placed and Twilio sends the webhook to your TwiML application, check the caller ID is valid at that point. If it isn't, respond to the webhook with a message using <Say> to tell the caller they are trying to call from an invalid caller ID and then <Hangup/>. If it is valid, then place the outbound call leg with <Dial>.
Let me know if that helps at all.

I found two ways to verify a callerID.
get a list of numbers from your account and loop through them as follows:
https://www.twilio.com/docs/voice/api/outgoing-caller-ids?code-sample=code-list-an-accounts-outgoing-caller-ids&code-language=PHP&code-sdk-version=6.x
$outgoingCallerIds = $twilio->outgoingCallerIds
->read([], 20);
foreach ($outgoingCallerIds as $record) {
print $record->sid.",".$record->phoneNumber.",".$record->friendlyName;
}
attempt the validate the number and watch for an error
https://www.twilio.com/docs/voice/api/outgoing-caller-ids#add-an-outgoing-caller-id
try{
$validation_request = $twilio->validationRequests
->create("+1".$cell, // phoneNumber
["friendlyName" => $name]
);
} catch (Throwable $e){
$pos=(strpos($e,"Phone number is already verified") );
if (is_numeric($pos) ) { do something }
}

Related

How can I get all envelopes status and their signers status in one request?

Is it possible to call the DocuSign API with the "docusign-client"-library in order to get status information about all envelopes with all of their recipients/signers in one request?
When we call the "EnvelopesApi.ListStatusAsync" method of the docusign client library we just retrieve an array of envelopes but without the status information of their signees.
public async Task<EnvelopesInformation> GetListStatus(EnvelopeIdsRequest envelopeIds, ListStatusOptions opt) {
return await Request(async api => await api.ListStatusAsync(settings.AccountId, envelopeIds, opt));
}
It seems that this information have to be determine in second request by calling
"EnvelopesApi.ListRecipientsAsync" method for every envelope.
Maybe someone have an idea or know how to call the API properly.
Are there any options we have to consider by calling the API or do we need to configure something in the DocuSign dashboard?
Thanks!
Remarks: In our environment we can't use webhooks. So we have to poll the DocuSign API.
No, it's not possible and maybe we should understand your statement about "we can't use webhooks".
My guess is that you have firewall or some private network and you can't have calls from outside into these servers. That's not a reason not to use webhooks.
There's a simple solution to this involving an intermediary cloud account that gets your webhooks and a queue mechanism for you to check for messages.
Here is a blog post by Larry that can help if you are willing to consider webhooks.
Yes, you're right. The main reason why we can't use webhooks is because the applicationn is behind a firewall and our customer do not want to make any changes on that.
Also I know the possibility of using DouSign with services like Azure or AWS to get notification about their bus-messaging system but this is something we do not want to implement yet. Maybe in the future.
We found out that we can use the "EnvelopesApi.ListStatusChangesAsync" method to get all of the status information we're interested in.
var options = new ListStatusChangesOptions {
envelopeIds = ids,
include = "recipients"
};
var result = await client.ListStatusChangesAsync(options);

How to retrieve all user tokens and send FCM to all

I am trying to send a FCM to multiple users at a time. I can't seem to find a clear answer other than using a topic but i have several conditions which make this quite difficult on my side. Is it at all possible to extract all tokens from a particular document (similar to setting it up as a topic but based on my logic) and pass that array to the Cloud function?
My current code is as follows and it works for a single user (i am only posting the part where the token is extracted):
return admin.firestore().doc('Seller_tokens/tokens/' + brand + '/wc').get().then(usertokensdoc =>{
const sellertokenID = usertokensdoc.get("dXufWMvOTLXUOyj8XNv9NFmsQ4x1");
const payload = {
data:{
title:'FCM - Test',
content: 'FCM - This is a test message,
},
token: sellertokenID
};
for the line:
const sellertokenID = usertokensdoc.get("dXufWMvOTLXUOyj8XNv9NFmsQ4x1");
I do not want to specify a single userid, where the 'userid' is the field in the document . And hence I would like to pass an array, if possible.
As you mentioned and as clarified in the official documentation Send messages to multiple devices, there are only two ways of sending messages to multiple tokens:
Firebase Cloud Messaging provides these two ways to target a message to multiple devices:
Topic messaging, which allows you to send a message to multiple devices that have opted in to a particular topic.
Device group messaging, which allows you to send a message to multiple devices that belong to a group you define.
In addition to this, as mentioned in this other question here, there is no API for you to get all tokens at once, so, you will need to get the individually for usage.
So, to summarize, there is not an automatic way of getting the tokens, but once you get them, I believe using the Device Messaging way would be better for you, since you can define specific groups to receive the FCM, per tokens that you retrieved.
Let me know if the information helped you!
you can retrieve the token documents based on your conditions in cloud function. loop through them, create an array of tokens and pass them to Firebase messaging as below
admin.messaging.sendToDevice(tokens, payload). below url has a very good example.
FCM - Cloud Functions Example

How to send client Call sid to newly transferred agent using Twilio node.js library without using Database

I'm working on a conference call scenario and want to transfer live call from one agent to other agent. When I transfer the call is there any method that I could use to send the Conference Name, ConferenceSid and client Call Sid to new agent. as response.send() sends values to existing client. Is there any method we can use to send these parameters to new agent? The API used is as follows.
client.conferences(conferences.sid)
.participants
.create({
from: '+183xxxxxxxxx',
to: `client:${agentNumber}`
})
.then(participant => console.log(participant));
Twilio developer evangelist here.
In this cold transfer scenario you already have the conference sid, as you show in your code. So, to find the conference name you can use the REST API to look it up.
client.conferences(conference.sid)
.fetch()
.then(conference => console.log(conference.friendlyName));
You can also fetch the conference participants. One of the call sids will be the call you created to your agent and the other will be the caller that is already on the line.
client.conferences('CFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.participants
.list()
.then(participants => {
participants.forEach(participant => console.log(participant.callSid));
});
Using these two API calls you can get the information for your new agent.
Let me know if this helps at all.

Stripe - create / retrieve customer in one call

Is there a stripe API call that we can use to create a user if they don't exist, and retrieve the new user?
say we do this:
export const createCustomer = function (email: string) {
return stripe.customers.create({email});
};
even if the user with that email already exists, it will always create a new customer id. Is there a method that will create a user only if the user email does not exist in stripe?
I just want to avoid a race condition where more than one stripe.customers.create({email}) calls might happen in the same timeframe. For example, we check to see if customer.id exists, and does not, two different server requests could attempt to create a new customer.
Here is the race condition:
const email = 'foo#example.com';
Promise.all([
stripe.customers.retrieve(email).then(function(user){
if(!user){
return stripe.customers.create(email);
}
},
stripe.customers.retrieve(email).then(function(user){
if(!user){
return stripe.customers.create(email);
}
}
])
obviously the race condition is more likely to happen in two different processes or two different server requests, than the same server request, but you get the idea.
No, there is no inbuilt way to do this in Stripe. Stripe does not require that a customer's email address be unique, so you would have to validate it on your side. You can either track your users in your own database and avoid duplicates that way, or you can check with the Stripe API if customers already exist for the given email:
let email = "test#example.com";
let existingCustomers = await stripe.customers.list({email : email});
if(existingCustomers.data.length){
// don't create customer
}else{
let customer = await stripe.customers.create({
email : email
});
}
Indeed it can be solved by validating stripe's customer data retrieval result against stored db.
And then call another API to create afterward.
However for simplicity sake, i agree with #user7898461 & would vouch for retrieveOrCreate customer api :)
As karllekko's comment mentions, Idempotent Keys won't work here because they only last 24 hours.
email isn't a unique field in Stripe; if you want to implement this in your application, you'll need to handle that within your application - i.e., you'll need to store [ email -> Customer ID ]s and do a lookup there to decide if you should create or not.
Assuming you have a user object in your application, then this logic would be better located there anyways, as you'd also want to do this as part of that - and in that case, every user would only have one Stripe Customer, so this would be solved elsewhere.
If your use case is like you don't want to create a customer with the same email twice.
You can use the concept of stripe idempotent request. I used it to avoid duplicate charges for the same order.
You can use customer email as an idempotent key. Stripe handles this at their end. the two request with same idempotent key won't get processed twice.
Also if you want to restrict it for a timeframe the create an idempotent key using customer email and that time frame. It will work.
The API supports idempotency for safely retrying requests without
accidentally performing the same operation twice. For example, if a
request to create a charge fails due to a network connection error,
you can retry the request with the same idempotency key to guarantee
that only a single charge is created.
You can read more about this here. I hope this helps

Getting customized message from GCM using Web push notifications

I'm using Web push notifications with Chrome, and they work great. But now I want to deliver a custom message in my notifications. I can have my Service Worker call out to my site to get content, as is done at https://simple-push-demo.appspot.com/—which is fine if I want every recipient to see the same message.
Is there any way to get either the recipient’s registration_id or the message_id that GCM returns? If I could get either of these and include them in the callback to the service, I could customize the response.
Also, any info on when we might be able to include a payload in the call to GCM?
The registration_id and message_id fields aren't exposed, but if the user is previously authenticated to your app, any fetch() to the server from your Service Worker will include credentials (and session information) which you can use to identify them.
If that doesn't work for your case, you can store user/session information in IndexedDB.
Payloads are coming soon—likely Chrome 50 or 51—based on the Web Push protocol. It's a bit of extra overhead and work to configure the (required) encryption.
It's possible, but I wouldn't do it since it's specific to GCM, while other browsers use other services.
You can either create a unique ID for each user (like we're doing in Mercurius) and store it in IndexedDB, or you can use the entire endpoint URL as an ID.
Here's the snippet to get the registration_id:
self.registration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
var endpoint = subscription.endpoint;
var endpointParts = endpoint.split('/');
var gcmRegistrationID = endpointParts[endpointParts.length - 1];
console.log(gcmRegistrationID);
}
});
P.S.: It returns a promise, so make sure your service worker waits for the promise to be resolved.

Resources