Twilio POST request using Alamofire on iOS - 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.

Related

iOS Swift - Authenticate wordpress user using Alamofire?

I want my app users to login with their Wordpress credentials. I've installed Alamofire & SwiftyJSON in order to do this, and I'm able to succesfully GET Wordpress endpoints to my app (via the Wordpress REST API). That said, I'm not sure how to authenticate my user on login?
I'm trying out the below, but the response is simply nil. Am I posting the user parameters to the wrong endpoint? Help is appreciated! I'm stumped.
let parameters: Parameters = [
"username": userField.text!,
"password": passField.text!,
]
AF.request("http://myurl.com/wp-json/wp/v2/users", method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success(let value):
if let json = value as? [String: Any] {
print(json["Result"] as? Int)
}
case .failure(let error):
print(error)
}
}
I accomplished this some time ago for WooCommerce. I imagine it would be similar to WordPress. I found two ways of doing this.
One way you would need a JWT. I use the free plugin "JWT Auth" by Useful Team. Using the username and password you obtain the token and sign in the user.
The other way is using HTTPS Authentication using Google Cloud Functions. I opened the WooCommerce login page using a WKWebView and added the Cloud Functions addresses as return and callback URLs.
I know the answer is vague but hopefully it will provide you with different ways to approach the task. Explaining the entire thing would be almost like a tutorial.

Push Twilio alerts to Slack Channel directly

I am not sure that there is way but can I send Twilio alerts from Twilio Console to Slack channel directly without using Python or any web framework that will listen to Twilio requests and send the data to Slack channel?
Using Twilio console, I can trigger a webhook from there once there is a new error but the Slack requires a data in the API.
Thank you
Twilio developer evangelist here.
It looks as though Slack expects webhooks to be in JSON format in a particular format, in the simplest form an object with a text property.
Twilio webhooks are sent in application/x-www-form-urlencoded format with the parameters listed here.
In order to turn this into a webhook that Slack will understand you will need some code or service that will translate the form encoded request into a JSON request with the right fields.
It seems you are reticent to build and host something yourself. If the hosting is the problem, can I suggest you look into Twilio Functions to build this. Twilio Functions lets you host JavaScript functions that can respond to incoming HTTP requests.
An example of a Twilio Function that could translate these alert webhooks into a Slack webhook might look like this:
const got = require('got');
exports.handler = async function (context, event, callback) {
const slackUrl = context.SLACK_URL;
const { ErrorCode, Description, AccountSid } = event;
const message = `New error for Twilio Account ${AccountSid}.\n\n${ErrorCode}: ${Description}`
try {
await got(slackUrl, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ text: message })
})
callback(null, "<Response/>");
} catch(error) {
callback(error);
}
}
The above code is untested, but should give you a good a start. It uses got to make the HTTP request to the Slack webhook URL. In this case, the webhook URL is stored in an environment variable.

How can I send HTML tag string in REST API by using Swift Alamofire?

I need to send HTML string to server.
I am using Swift alamofire and when I try to call Rest api then getting ccs code response from server.
same body format used in PostMan and it's working good.
My request body parameters:
{body = "<br/><br/>Hi Bhavdip,<br/><br/>Please find the One-Time Password (OTP) as requested through application.<br/>OTP- 123456 <br/><br/>Kindly, enter this OTP in your mobile application to authenticate your account and change phone number.<br/><br/>Kind regard,<br/>VeriDoc Global Team.";subject = "VeriDoc Global OTP for Account Verification";toaddress = "bambhroliya.bhavdip#example.com"; toname = "Bhavdip Patel";}
Response:
invalid json format. getting css code.
Param Value is
"<br/><br/>Hi Bhavdip,<br/><br/>Please find the One-Time Password (OTP) as requested through application.<br/>OTP- 123456 <br/><br/>Kindly, enter this OTP in your mobile application to authenticate your account and change phone number.<br/><br/>Kind regard,<br/>VeriDoc Global Team."
let params = [body = "<br/><br/>Hi Bhavdip,<br/><br/>Please find the One-Time Password (OTP) as requested through application.<br/>OTP- 798580 <br/><br/>Kindly, enter this OTP in your mobile application to authenticate your account and change phone number.<br/><br/>Kind regard,<br/>VeriDoc Global Team.",subject = "VeriDoc Global OTP for Account Verification",toaddress = "bambhroliya.bhavdip#tristonsoft.com", toname = "Bhavdip Patel"] as! [String:Any]
use this as your params

How to send Dialogflow an access token from Swift using ApiAi Pod

While following this tutorial: https://medium.com/#pallavtrivedi03/integrating-dialogflow-as-a-chat-bot-in-an-ios-app-e66a4c7f2723
I was unable to find out how to interact with dialogflow intents that require authentication via the swift app. Once the dialogflow path reaches a point where it needs authentication, the request is not met with a response.
I have successfully sent requests and received responses from dialogflow using the following:
func performQuery(senderId:String,name:String,text:String)
{
let request = ApiAI.shared().textRequest()
if text != "" {
request?.query = text
} else {
return
}
//print("request: ")
request?.setMappedCompletionBlockSuccess({ (request, response) in
let response = response as! AIResponse
print(response.result.parameters)
//print(response.result.action)
I am not an experienced swift user so it could be that I am missing something simple, however, I am unable to find any documentation on the topic.
Any information on ways to interact with dialogflow using oauth2 would be greatly appreciated.

Sending sms from iOS app using Plivo API swift

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)

Resources