AlamoFire for twilio - ios

I am trying to send a post request for the twilio api using swift and Alamofire, but I am having some issues.
This is the function that should send the text:
func sendSMS() {
let parameters = [
"To": "+12036044632",
"From": "+13852322267",
"Body": "Hi daddy"
]
Alamofire.request(.POST, "https://MY SID:MY SECRET#api.twilio.com/2010-04-01/Accounts/MY SID/Messages", parameters: parameters).response { response in
print(response.0)
print(response.1)
print(response.2)
print(response.3)
}
}
When I run this, I get this printed in the console:
`Optional(<NSMutableURLRequest: 0x7a844a30> { URL: https://AC11ed62fdb971a8f56d9be531a5ce40c2:UKCkDN1ojSeT4L27lc8uaNQ5qsvPJgMxd#api.twilio.com/2010-04-01/Accounts/AC11ed62fdb971a8f56d9be531a5ce40c2/Messages })
Optional(<NSHTTPURLResponse: 0x7a9f91f0> { URL: https://AC11ed62fdb971a8f56d9be531a5ce40c2:UKCkDN1oj2SeT4L7lc8uaNQ5qsvPJgMxd#api.twilio.com/2010-04-01/Accounts/AC11ed62fdb971a8f56d9be531a5ce40c2/Messages } { status code: 401, headers {
"Access-Control-Allow-Credentials" = true;
"Access-Control-Allow-Headers" = "Accept, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since";
"Access-Control-Allow-Methods" = "GET, POST, DELETE, OPTIONS";
"Access-Control-Allow-Origin" = "*";
"Access-Control-Expose-Headers" = ETag;
Connection = "keep-alive";
"Content-Length" = 327;
"Content-Type" = "application/xml";
Date = "Tue, 02 Aug 2016 02:21:01 GMT";
"Twilio-Request-Duration" = "0.004";
"Twilio-Request-Id" = RQ36001aed85114ea18c7eac4f20caaf59;
"Www-Authenticate" = "Basic realm=\"Twilio API\"";
"X-Powered-By" = "AT-5000";
"X-Shenanigans" = none;
} })
Optional(<3c3f786d 6c207665 7273696f 6e3d2731 2e302720 656e636f 64696e67 3d275554 462d3827 3f3e0a3c 5477696c 696f5265 73706f6e 73653e3c 52657374 45786365 7074696f 6e3e3c43 6f64653e 32303030 333c2f43 6f64653e 3c446574 61696c3e 596f7572 20416363 6f756e74 53696420 6f722041 75746854 6f6b656e 20776173 20696e63 6f727265 63742e3c 2f446574 61696c3e 3c4d6573 73616765 3e417574 68656e74 69636174 696f6e20 4572726f 72202d20 4e6f2063 72656465 6e746961 6c732070 726f7669 6465643c 2f4d6573 73616765 3e3c4d6f 7265496e 666f3e68 74747073 3a2f2f77 77772e74 77696c69 6f2e636f 6d2f646f 63732f65 72726f72 732f3230 3030333c 2f4d6f72 65496e66 6f3e3c53 74617475 733e3430 313c2f53 74617475 733e3c2f 52657374 45786365 7074696f 6e3e3c2f 5477696c 696f5265 73706f6e 73653e>)
nil`
I then do not get a text message, and also on the Twilio console, it does not count and does not charge me. Am I getting some kind of error? What am I doing wrong?
Note: I understand the security risks of having the auth in the url, and that is not the fix I am looking for so please do not post or comment about that. Thanks

Instead of:
Alamofire.request(.POST, "https://MY SID:MY SECRET#api.twilio.com/2010-04-01/Accounts/MY SID/Messages", parameters: parameters).response { response in
print(response.0)
print(response.1)
print(response.2)
print(response.3)
}
Try this:
Alamofire.request(.POST, "https://MY SID:MY SECRET#api.twilio.com/2010-04-01/Accounts/MY SID/Messages", parameters: parameters)
.authenticate(user: user, password: password)
.responseJSON { response in
let response = String(response.result.value)
print(response)
}
You have to authenticate correctly into Twilio using Alamofire, and that is what ".authenticate" is for. Change the variable user to your account SID, and change the variable password to your auth token. Reference https://www.twilio.com/console/account/settings to find your account SID and auth token.
You can then manipulate the response string however you'd like.
Hope this helps.

{ status code: 401
It means you're not authenticated. It is possible that your AccountSid or AuthToken was incorrect. If you like to check your credentials, you can try first from your computer with curl and once you get it working you can move to Alamofire.
Example request with curl
curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/ACc0966dd96e4d55d26ae72df4d6dc3494/Messages.json' \
--data-urlencode 'To=+16518675309' \
--data-urlencode 'From=+14158141829' \
--data-urlencode 'Body=Hey Jenny! Good luck on the bar exam!' \
-u ACc0966dd96e4d55d26ae72df4d6dc3494:[AuthToken]
docs at https://www.twilio.com/docs/api/rest/sending-messages

Related

I'm unable to get my API token using the below POST code

I am trying to get a authentication token using this code below, i am kind of confused on how to go about it.
url = "https://api.tradingcentral.com/authentication/v3"
headers = {"accept: application/json",
"Content-Type: application/json"}
data = {"clientId": "rc-xxx", "password": "4xxxxxxxxxx", "endUserId": "testuserid", "admin": 'false'}
response = requests.post(url = url, headers=headers, params=data)
df = response.text
I seem to be doing something wrong.

Unauthorized Error 401 Get OAUTH2 Token for paypal in Angular

I am working on paypal recurring payment and i need token to get subscriber information to allow it login. But i got unauthorized error. Here is my code
getTokan():Observable<any>{
let client_id = '411820721167-jcuj1jeae0l1j06i3q2otsnol2phlqem.apps.googleusercontent.com';
let secret = 'pe7berpzDSlwDVpgj-NQvseP';
let key = client_id+':'+secret;
let headers = new HttpHeaders({
"Accept": "application/json",
"Accept-Language": "en_US",
'Authorization': 'Basic '+key,
'Content-Type': 'application/x-www-form-urlencoded',
});
let options = { headers: headers };
return this.http.post<any>('https://api.sandbox.paypal.com/v1/oauth2/token',"grant_type=client_credentials", { headers: headers })
}
Explain me what is client id and secret. I am using sandbox client Id secret. i got this error.
zone-evergreen.js:2845 POST https://api.sandbox.paypal.com/v1/oauth2/token 401 (Unauthorized)
That is not a PayPal REST APP's clientId and secret. Get a pair for from the sandbox tab of https://www.paypal.com/signin?intent=developer&returnUri=https%3A%2F%2Fdeveloper.paypal.com%2Fdeveloper%2Fapplications
Also, they must be Base64 encoded in your request

Reddit API Add Friend Endpoint /api/friend

Whenever I attempt to make a PUT Request to Reddit API in order to add a friend, it fails and claims a JSON Parse Error 'JSON_PARSE_ERROR'. Nothing I do is working. Here is how I form the request.
Endpoint: /api/v1/me/friends/username
>>> Endpoint URL: PUT https://oauth.reddit.com/api/v1/me/friends/micheal
Authorization: Bearer <Access_Token>
// The response given:
{"fields": ["json"], "explanation": "unable to parse JSON data", "reason": "JSON_PARSE_ERROR"}
I have also tried the /api/friend/username endpoint and nothing works.
I had exactly the same problem, and your question led me to the solution.
The endpoint is expecting a json payload ACTUALLY NAMED "json." I'm not sure what language you're using, this is what it looks like in Node:
var options = {
url: 'https://oauth.reddit.com/api/v1/me/friends/mynewfriend',
headers: {
'User-Agent': 'Appname/1.0 by username',
'Authorization': "bearer " + <Access_Token>
},
json: {
'name': 'mynewfriend',
'notes': 'whatever notes you want to put',
}
};
request.put(options, function(error, response, body) {
blah blah blah
}
the json itself is described in https://www.reddit.com/dev/api/#PUT_api_v1_me_friends_{username}

io9 - Alamofire token request fails with 401 error depsite curl from debugPrint works

My question is along the line of a question which has been asked before at Previous question.
I am using Alamofire 3.2.1, XCode 7.3, iOS9.
Here is my code with the intention to obtain a token from OAuth server (localhost) implemented by django oauth toolkit:
let params = ["grant_type": "password",
"username": "rosa",
"password": "rosa1234"]
let request = Alamofire.request(.POST, url, parameters: params).authenticate(user: __clientID, password: __clientSecret)
debugPrint(request)
request.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseSwiftyJSON({ (request, response, json, error) in
debugPrint(response)
if (error != nil) {
print(error.debugDescription)
return completionHandler(token: nil, error: error)
}
// call the completionHandler function (object) to deal with data further
return completionHandler(token: json.string, error: nil)
})
The debug print of request gives a working curl command, which works on a command line:
curl -i \
-X POST \
-u PrtRUN9ra7LHCYWbiReaAjO9I26lJhLhRSAUJgtr:kTvxqKmClDAL3tbdyZdyBZgsfsfXtagMpZyFjSZwpIknxM43l6ZIvJxJGXu2J2FuHf4JMLfopDoAzkF6vHSRq4GZkbnEZSmmUnMvkhMvSucbhWUdzCpxuj9qtc8beaQ3 \
-H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" \
-H "User-Agent: IntelliCafe/xsoft.IntelliCafe (1; OS Version 9.3 (Build 13E230))" \
-H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
-H "Accept-Language: en-US;q=1.0" \
-d "grant_type=password&password=rosa1234&username=rosa" \
"http://localhost:8000/o/token/"
But the code does not work in my app. The error is 401:
Optional(<NSHTTPURLResponse: 0x7d183950> { URL: http://localhost:8000/o/token/ } { status code: 401, headers {
"Cache-Control" = "no-store";
"Content-Type" = "application/json";
Date = "Mon, 11 Apr 2016 20:43:48 GMT";
Pragma = "no-cache";
Server = "WSGIServer/0.1 Python/2.7.10";
"X-Frame-Options" = SAMEORIGIN;} })
Optional(Error Domain=com.alamofire.error Code=-6003 "Response status code was unacceptable: 401" UserInfo={NSLocalizedFailureReason=Response status code was unacceptable: 401})
This problem is driving me crazy. Any help will be grateful!
Thanks in advance.
I wrote a django rest view to print out the meta data of the request and found out the clientID and clientSecret are not embedded/processed properly by the django server implementation.
Using the Authorization header as shown in Alamofire documentation works.

Devise_token_auth - unable to run controller action

I am currently building an iOS app which communicates with a ruby-on-rails api. The user management(sign_in, sign_out,...) part of the api is handled with devise_token_auth gem.
I am also using Alamofire to run HTTP requests.
I am currently testing two apis:
POST /api/auth/sign_in(.:format) devise_token_auth/sessions#create
POST /api/posts(.:format) api/posts#create
The first api is used to login while the second creates posts. FYI, in my posts_controller, I am using before_action :authenticate_user! to prevent non authenticated users to create posts.
Here is what I want to do:
Sign in from the client side (iOS app) --> the sign_in api returns the access-token
Create a post from the client side using the access-token.
I managed to get the access-token using this code:
let parameters = [
"email":"omar#omar.com",
"password":"password"]
Alamofire.request(.POST, "http://localhost:3000/api/auth/sign_in", parameters: parameters)
.responseJSON { response in
// get my access token and store it.
}
When I try to create a post(2nd part), here is what I did :
let headers = ["access-token":"<my-token-value>",
"token-type": "Bearer",
"uid":"omar#omar.com"]
let parameters = [
"title":"this is a title",
"body":"this is a body"]
Alamofire.request(.POST, "http://localhost:3000/api/posts", parameters: parameters, headers: headers)
.responseJSON { response in
print(response.response) // URL response
}
When printing the response, here is what I get:
Optional(<NSHTTPURLResponse: 0x7fe422f2b670> { URL: http://localhost:3000/api/posts } { status code: 401, headers {
"Cache-Control" = "no-cache";
Connection = "Keep-Alive";
"Content-Length" = 37;
"Content-Type" = "application/json; charset=utf-8";
Date = "Thu, 03 Mar 2016 15:03:27 GMT";
Server = "WEBrick/1.3.1 (Ruby/2.2.1/2015-02-26)";
"Set-Cookie" = "request_method=POST; path=/";
Vary = Origin;
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-Request-Id" = "82a88799-3fac-42e0-bd01-db5b7e24fcda";
"X-Runtime" = "0.045969";
"X-Xss-Protection" = "1; mode=block";
} })
Also, on Rails server logs:
Filter chain halted as :authenticate_user! rendered or redirected
Completed 401 Unauthorized in 15ms (Views: 0.8ms | ActiveRecord: 4.4ms)
Does anyone know where the error is coming from?
I finally found the solution. Beside expecting the access-token, the token-type and the uid, my API was also expecting the client id in the headers. This client id is sent at the sign_in request response.

Resources