HTTP POST response is not deliverd properly rails - ruby-on-rails

I am working with rails application. In my development environment an API makes a HTTP POST request to my application and the application have to respond it accordingly. Every thing is working just fine up to receive the request and respond it with the status 200.
But the response is not delivered successfully to the requesting API.
Here is my code to respond the request
def mysomething
if params[:secret] != webhook_secret
response = {text: "Invalid webhook secret", status: 401}
else
if params[:event] == 'incoming_message'
content = params[:content];
from_number = params[:from_number];
phone_id = params[:phone_id];
result = {messages: {content: "Thanks for your message!"}}
else
result = {messages: {content: "invalid event"}}
end
response = {json: result.to_json, status: 200}
end
render response
end
Can anyone tell me where is the problem? why it is not forwarded to the API.
THANKS

try this
render :json => response

Related

how to handle webhook responses sent through API in rails

I am using an API to post request, and i received a response from API, but then this API will continue send POST request to webhook, how can i capture the response from Webhook.
def request_api(number)
url = 'http://localhost:3550/call'
#response = HTTParty.post(
url,
:body=> { :phone => "#{number}",
:webhookURL => "http://localhost:3550/call"}.to_json,
:headers => {
'Content-Type' => 'application/json',
'Authorization' => '77d22458349303990334xxxxxxxxxx'
}
)
render json: #response
end
I can see the POST request sent by API in server.ts, and there is a status, how can i capture this status in rails.
POST http://localhost:3550/call (id=1267 status=completed) - received response code=200
Try render json: { status: :ok } instead of render json: #response to send back a response to the API that your server has received webhook successfully. That way you can prevent API keep sending you same webhook again and again.
Use params to capture the response received with the webhook.

Rails: return only integer in get method

I am trying to setup Facebook's webhook, and when specifying the callback url, they send a get request to it and expect to receive a code.
I defined an action:
def webhook
render json: { code: '1234567890' }
end
So the reponse to the request is { code: '1234567890' } when they are expecting '1234567890'.
I tried to only have:
def webhook
render json: {'1234567890'}
end
But I get an error.
I also tried to use the head method but nothing is sent back.
How can I only send back an integer ?
As Nani pointed it out in the comments:
def webhook
render :json => 1826416246
end
Works fine !

401 unauthorized response empty in ios if sent via custom failure app

class CustomFailureApp < Devise::FailureApp
# You need to override respond to eliminate recall
def respond
if http_auth?
http_auth
else
if request.format == "application/json"
self.status = 401
self.content_type = "json"
self.headers['WWW-Authenticate']="Please Confirm Your Account To Continue"
self.response_body = {error: I18n.t("devise.failure.inactive")}.to_json
else
redirect
end
end
end
end
whenever the user is unconfirmed spree_auth_devise respond with unauthorized which is handled by my custom failure app but the response object received by the ios app is empty.
ios app is using AFNetworking and is updated to latestmaster
I can't get what I am doing wrong.
I found out that there is nothing wrong with this code , on the contrary the ios response handler was faulty.

Getting 401 response when connecting to Google via OAuth2, Ruby

I'm trying to access all the contacts from Google Contacts for invite purposes from my site.
So I'm using OAuth2 but when I first request I get a 401 error with access_token. :(
Keep in mind I'm working local!!
Here's my code.
def authenticate
# initiate authentication w/ gmail
# create url with url-encoded params to initiate connection with contacts api
# next - The URL of the page that Google should redirect the user to after authentication.
# scope - Indicates that the application is requesting a token to access contacts feeds.
# secure - Indicates whether the client is requesting a secure token.
# session - Indicates whether the token returned can be exchanged for a multi-use (session) token.
next_param = "http://localhost:3000/import/authorise"
scope_param = "https://www.google.com/m8/feeds/"
#session_param = "1"
state="profile"
client_id="535946964206.apps.googleusercontent.com"
root_url = "https://accounts.google.com/o/oauth2/auth"
response_type="token"
#TO FIND MORE ABOUT THESE PARAMETERS AND THERE MEANING SEE GOOGLE API DOCS.
query_string = "?scope=#{scope_param}&state=#{state}&redirect_uri=#{next_param}&response_type=#{response_type}&client_id=#{client_id}"
#render :text=> root_url + query_string and return
# redirect_to "https://accounts.google.com/o/oauth2/auth?
#scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&
#state=%2Fprofile&
#redirect_uri=http://localhost:3000/import/authorise&
#response_type=token&
#client_id=535946964206.apps.googleusercontent.com
#"
redirect_to root_url + query_string
end
this is for authentication now i get response with access token
http://localhost:3000/import/authorise#state=profile&access_token=ya29.1.AADtN_WPohnlKYBH16kFrqEcYUTZ558WDICpqCqiz1mwBKESFr5PTiJFA5vsyoc&token_type=Bearer&expires_in=3600
Now next it will redirected to here,this is where i get above error
# YOU WILL BE REDIRECTED TO THIS ACTION AFTER COMPLETION OF AUTHENTICATION PROCESS WITH TEMPORARY SINGLE USE AUTH TOKEN.
def authorise
#FIRST SINGEL USE TOKEN WILL BE RECEIVED HERE..
token = params[:token]
#PREPAIRING FOR SECOND REQUEST WITH AUTH TOKEN IN HEADER.. WHICH WILL BE EXCHANED FOR PERMANENT AUTH TOKEN.
uri = URI.parse("https://www.google.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
path = '/accounts/AuthSubSessionToken'
headers = {'Authorization' => "AuthSub token=#{token}"}
render :text=> http.get(path, headers) and return
#GET REQUEST ON URI WITH SPECIFIED PATH...
resp, data = http.get(path, headers)
#ender :text=> data and return
resp.code="200"
#SPLIT OUT TOKEN FROM RESPONSE DATA.
if resp.code == "200"
token = ''
data.split.each do |str|
if not(str =~ /Token=/).nil?
token = str.gsub(/Token=/, '')
end
end
return redirect_to(:action => 'import', :token => token)
else
redirect_to root_url , :notice => "fail"
end
end
here at above function when it requests resp, data = http.get(path, headers) the responce resp.code is 401 . i dont know what's wrong i'm following https://gist.github.com/miketucker/852849 example which uses AuthSub which is now not in use so i'm adapting oauth2 .
i already have made app at clode console and given return url and other info.
any help or point me to other working example,thanks you!!!
thank you.

Rubymotion: GET Request using JSON

I am new to iOS programming and using Rubymotion to build my first application. In my Rubymotion app I POST to a webserver (an app built using RoR) to authenticate a user wanting to Login and am using the BubbleWrap gem for RubyMotion https://github.com/rubymotion/BubbleWrap/blob/master/motion/http.rb
def login(sender)
payload = {email: #email, password: #password}
BubbleWrap::HTTP.post("http://example.com/sessions", {payload: payload}) do |response|
#authCookie = response.headers['Set-Cookie']
end
end
Now once I receive successful authentication I move onto to receive JSON data from the web application using the following code:
BubbleWrap::HTTP.get("http://example.com/events.json", {cookie: #authCookie, :headers=>{"Content-Type"=>'json'} }) do |response|
puts response.body #testing the response
end
For some reason, the authentication token received from the POST request is not being correctly passed on by the GET request. I know this because in the web app if authentification fails it redirects to the login page and that's the response (HTML code of the Login page) am receiving from the GET request.
Authentication check on the Web App:
def session_check
if session[:bizid].nil?
redirect_to login_url
flash[:notice] = "Please login to view your account!"
end
end
Additionally, on the web app this authentication token is set by the following method:
def create
current_biz = Bizname.find_by_email(params[:email])
if current_biz && current_biz.authenticate(params[:password])
session[:bizid] = current_biz.id
flash[:notice] = 'Login Successful!'
if current_biz.events.empty?
redirect_to getsetup_url
else
redirect_to account_summary_url
end
else
flash[:notice] = 'Incorrect Email or Password.'
redirect_to login_url
end
end
Any ideas of what I might be doing wrong here?
Thanks in advance!
You just need to pass the cookie in as a header too. For example:
BubbleWrap::HTTP.get("http://example.com/events.json", :headers=> {"Content-Type"=>'json', "Cookie" => #authCookie}) do |response|
puts response.body #testing the response
end

Resources