Sending sms from iOS app using Plivo API swift - ios

How do I use plivo SMS API in my iOS app using Swift. I read lot of documentation regarding this. I'm not sure how to implement it on swift.
var plivo = require('plivo');
var p = plivo.RestAPI({
authId: 'Your AUTH_ID',
authToken: 'Your AUTH_TOKEN'
});
var params = {
'src': '1111111111', // Sender's phone number with country code
'dst' : '2222222222', // Receiver's phone Number with country code
'text' : "Hi, text from Plivo", // Your SMS Text Message - English
//'text' : "こんにちは、元気ですか?", // Your SMS Text Message - Japanese
//'text' : "Ce est texte généré aléatoirement", // Your SMS Text Message - French
'url' : "http://example.com/report/", // The URL to which with the status of the message is sent
'method' : "GET" // The method used to call the url
};
// Prints the complete response
p.send_message(params, function (status, response) {
console.log('Status: ', status);
console.log('API Response:\n', response);
console.log('Message UUID:\n', response['message_uuid']);
console.log('Api ID:\n', response['api_id']);
});
The above code is in Node.js, I want it to write in swift, and also I'm not sure how to integrate plivo into iOS app. I'm developing an app where it should send a sms to admin whenever user requests an order. So I just want the outgoing message from Plivo to admin. Any suggestions is really helpfull.

Plivo Sales Engineer here. Our recommendation is to host a server to which your iOS app would make a request to send the SMS. Then your server can use a Plivo helper library to make the API request which would send the SMS. This way your AuthID and AuthToken are stored on your server (to which only you have complete access) and you don't expose your Plivo credentials in your iOS app.
If you make a direct request of the Plivo API from your iOS app, then users potentially could find and misuse your credentials.
tl;dr - don't put your authentication credentials in places other people can read it.

So without a helper library you will have to just make use of their REST API. From their site, sending an SMS can be done by POSTing your information to
https://api.plivo.com/v1/Account/{auth_id}/Message/
As for the Swift part take a look at NSMutableURLRequest or if you need help with the networking request you can look at Alamofire

If you want to use Rest API you can do like this:
lazy var plivoRestAPI: PlivoRest = {
let rest = PlivoRest(authId: Constants.Credentials.Plivo.AuthId,
andAuthToken: Constants.Credentials.Plivo.AuthToken)!
rest.delegate = self
return rest
}()
let params = ["to": phoneNumberToCall,
"from": "1111111111",
"answer_url": "",
"answer_method": "GET"]
plivoRestAPI.callOutbound(params)

Related

How to integrate audio call(User to User) using twilio API?

I want to integrate user to user audio call feature using Twilio API, is it possible in Twilio? if yes can you please provide a tutorial.
Here I have added the code:
1. For get token from the Twilio
$.post(url, function(data) {
// Set up the Twilio Client Device with the token
Twilio.Device.setup(data.token);
});
and it returns the token using function
public function newToken(Request $request, ClientToken $clientToken)
{
$forPage = $request->input('forPage');
$twilio = config('services.twilio');
$applicationSid = $twilio['applicationSid'];
$clientToken->allowClientOutgoing($applicationSid);
if ($forPage === route('dashboard', [], false)) {
$clientToken->allowClientIncoming('support_agent');
} else {
$clientToken->allowClientIncoming('customer');
}
$token = $clientToken->generateToken();
return response()->json(['token' => $token]);
}
When I make a call following javascript function start
function callCustomer(phoneNumber) {
updateCallStatus("Calling " + phoneNumber + "...");
var params = {"phoneNumber": phoneNumber};
Twilio.Device.connect(params);
}
and then browser ask for the enable microphone and after allowing it plays the small audio say's that "Application error occurred, Good bye!".
Twilio voice call please refer the following documentation step by step
QuickStartDemo
Twilio developer evangelist here.
The TwiML connects the outgoing call to the other user. When you set up the TwiML Application for outgoing calls you need to set a voice URL. When you make the call using Twilio.Device.connect then Twilio Client will connect to Twilio, Twilio will then make an HTTP request to the voice URL of your TwiML app, passing along the parameters that you send, to find out what to do with the call.
You are passing in a phoneNumber parameter, so that will be passed to your application. You've tagged this question with PHP, so here's an example (using the Twilio PHP library) of what you could do to dial onto the phone number that you are passing.
<?php
require_once './vendor/autoload.php';
use Twilio\Twiml;
$phoneNumber = $_REQUEST['phoneNumber'];
$response = new Twiml();
$dial = $response->dial();
$dial->number($phoneNumber);
echo $response;
Check out the documentation on Twilio Client for more details on how this works.

How to access data field in Dialogflow?

As the Dialogflow documentations states, the data field represents
Additional data required for performing the action on the client side.
The data is sent to the client in the original form and is not
processed by Dialogflow.
How should one access it in the iOS framework?
request?.setMappedCompletionBlockSuccess({ (request, response) in
...
}
I couldn't find it in the response object and can't find any documentation for iOS.
Thanks.
Your question is a bit vague (can you edit and narrow it down?), but i think you got it the other way round, what that snippet of documentation that you pasted means is that you are supposed to send that payload to DialogFlow and it will forward it to a connected Client (e.g Messenger, Slack etc) un-touched. It simply means that DialogFlow assumes that you know what you are doing.
Here is a sample Fulfilment response to DialogFlow in JS
module.exports.sendGenericMessageWithText = function(message) {
return {
data: {
facebook: [
{
text: message
]
}
}
}

Twilio POST request using Alamofire on iOS

I have this IBAction that is supposed to simply test sending SMS:
let todosEndpoint: String = "https://api.twilio.com/2010-04-01/Accounts/\(ACCOUNT_SID)/Messages.json"
let message = ["To": "+1555...5555", "From": "+555...5555", "Body": "Hello!"]
for item in message {
print(item)
}
Alamofire.request(todosEndpoint, method: .post, parameters: message, encoding: JSONEncoding.default)
.authenticate(user: ACCOUNT_SID, password: ACCESS_TOKEN)
.responseJSON { response in
debugPrint(response)
}
However, I'm getting this as a response:
[Result]: SUCCESS: {
code = 21603;
message = "A 'From' phone number is required.";
"more_info" = "https://www.twilio.com/docs/errors/21603";
status = 400;
}
I am sure I am providing the right phone number and authentication and I've used python to test sending messages using my API key and phone number.
Is the structure of my dictionary wrong or something?
Thank you for any help!
Twilio developer evangelist here.
We do not recommend that you make API calls directly to Twilio from your application. You would need to include your account credentials in the application somehow, so a malicious attacker could decompile the app, extract your details and abuse your Twilio account.
Instead, we recommend you set up a server of your own that can keep the credentials safe and then make requests to that yourself. Check out this blog post on sending SMS messages on iOS with Twilio, Swift and Alamofire.

Getting notified in another browser when a chat message is sent in Twilio

I am sending messages in using Twilio using this code:
string channelId = <channelId>;
string serviceSid = <servicesid>;
IpMessagingClient ipMessagingClient = new IpMessagingClient(<accountid>, <token>);
var msgResult = ipMessagingClient.CreateMessage(serviceSid, channelId, "sender", "message");
msg.Body = "body"
msg.DateSent = DateTime.Now;
msg.Sender = "sender"
return Json(new
{
Success = msgResult.Sid != null,
NewMessage = msg
});
Message is sent just fine and I can retrieve the messages of the channel. What I am trying to achieve now is other open browser and in the channel gets notified of new messages sent so I can update the UI to display the new messages without manual refreshing the browser.
Twilio developer evangelist here.
It looks like you are using the REST API to send messages to the Programmable Chat API.
To get using the client versions, the JS client in particular, I would take a read through the Programmable Chat documentation, go download the JS SDK and take a look at the code for the reference chat demo. All of those bits should give you a good grounding in building chat for the client side.
Let me know if that helps at all.

Twilio check if phone number has been blacklisted

I am currently integrating into the twilio rest api and need to perform a check on a users phone number to determine if that user has blacklisted themselves or not. I have little experience with this api and scouring through the documentation and google has turned up nothing.
In our application we are going to have a notification center and if the user has blacklisted themselves I do not want to give them the ability to turn on their SMS notifications. Potentially a user could have SMS notifications on but twilio would block any messages. I know there is the ability to get a status code back from twilio when an SMS is queued that shows the user is blacklisted (https://www.twilio.com/docs/api/rest/message). However, I will not be sending messages on the notifications screen and need a direct way (if at all possible) to check twilio to determine if a number is blacklisted. Any help is much appreciated. Let me know if anymore information will be of help.
Megan from Twilio.
I'd be curious to see if you ever tried your own workaround. But I wanted to note for others in a similar situation how you could grab the blacklist error and then do whatever you may want with it.
In Ruby it would look something like this:
require 'rubygems'
require 'twilio-ruby'
account_sid = 'YOUR_ACCOUNT_SID'
auth_token = 'YOUR_AUTH_TOKEN'
#client = Twilio::REST::Client.new account_sid, auth_token
begin
#message = #client.messages.create(
from: 'TWILIO_NUMBER',
to: 'USER_NUMBER',
body: 'Howdy!'
)
rescue Twilio::REST::RestError => e
if e.code == 21610
# User is blacklisted
# Store info however you choose
puts e.message
end
end
We check for blacklisting specifically using the code '21610'. For more information about errors you can visit the reference page.
Hope this helps!
Twilio recommends developers to store the opt-out/in statuses in their side. I have stored it in DB. There are 2 ways to collect the unsubscribed users list.
1) Use SMS webhooks. You can find how to configure your Twilio number to receive webhook events here
#PostMapping(value = "/twilio", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.APPLICATION_ATOM_XML_VALUE)
public String twilioConsumer(TwilioEventDTO twilioEventDTO) {
// twilioEventDTO.getBody() => returns the body of the SMS user replied.
twilioService.consume(twilioEventDTO);
return new MessagingResponse.Builder().build().toXml();
}
2) Since I implemented webhooks later, I had to collect already unsubscribed users. When you send sms to the number that has been opted-out, Twilio API throws an exception with the status number of 21610. You can catch it and store the number in DB.
try {
Message result = Message.creator(
new PhoneNumber(toPhoneNumber),
new PhoneNumber(fromPhoneNumber),
messageBody)
.create();
response = result.getStatus().name();
} catch (ApiException e) {
if (e.getCode().equals(21610))
updateSubscription(toPhoneNumber, false);
logger.warn("Error on sending SMS: {}", e.getMessage());
}
P.S.: examples written in Java - Spring Boot framework.

Resources