iphone can't post to my rails app - iphone

So I have been trying out several different ways to connect my iPhone app to my ROR restful backend and all seems to work ok pulling down data (json) with 'get' requests, but when posting I am unable to do so. I have tried ObjectiveResource and two or three others and they all have the same issue. I am thinking its something set wrong in my ROR app? I did notice all the example iPhone projects use https for production apps, does a production app need to https for an iPhone to establish a session and be able to post?
HERE is what I get for an error if I use http://localhost:3000/posts
Processing PostsController#create (for 127.0.0.1 at 2011-04-05 20:49:42) [POST]
Parameters: {"post"=>{"budget"=>"222"}}
User interests hash: false
NoMethodError (undefined method posts' for false:FalseClass):
app/controllers/posts_controller.rb:113:increate'
If I use http://localhost:3000
Processing PostsController#index (for 127.0.0.1 at 2011-04-05 20:49:42) [POST]
Parameters: {"post"=>{"budget"=>"222"}}
Here is my Create method:
def create
##post = Post.new(params[:post])
#post = current_user.posts.build(params[:post])
respond_to do |format|
if #post.save
flash[:notice] = 'Post was successfully created.'
format.html { redirect_to(#post) }
format.xml { render :xml => #post, :status => :created, :location => #post }
format.json { render :json => #post, :status => :created, :location => #post }
else
format.html { render :action => "new" }
format.xml { render :xml => #post.errors, :status => :unprocessable_entity }
format.json { render :json => #post.errors, :status => :unprocessable_entity }
end
end
end
Here is the method:
# POST /posts
# POST /posts.xml
def create
##post = Post.new(params[:post])
#post = current_user.posts.build(params[:post])
respond_to do |format|
if #post.save
flash[:notice] = 'Post was successfully created.'
format.html { redirect_to(#post) }
format.xml { render :xml => #post, :status => :created, :location => #post }
format.json { render :json => #post, :status => :created, :location => #post }
else
format.html { render :action => "new" }
format.xml { render :xml => #post.errors, :status => :unprocessable_entity }
format.json { render :json => #post.errors, :status => :unprocessable_entity }
end
end
end
Iphone call:
// CRUD methods using Resource.h
- (void)createRemote {
NSString *url =
[NSString stringWithFormat:#"%#/posts", siteURL];
[Resource post:[self params] to:url];
}
%#/posts is equal to http://localhost:3000/posts

Do you have protect_from_forgery set on your ApplicationController?
This essentially kills POSTing information from anywhere except the forms on your website. Try commenting it out and see if things start working.

As peterjb said, check for forgery protection. If you're on rails 3 then look for the csrf_meta_tag in your application.html.erb.

https -- is not must, it is how your server configures for the security needs. You can have http and https both no issues.
I suggest you to have look at the log in ROR app end too know what you get HTTP POST data -- if you are not able to get any data in ROR app end post some code which does POST request from your iPhone, people can analyse it better.

Related

How to integrate instamojo payment gateway with codeigniter rest server?

I am trying to integrate Instamojo Payment Gateway within Chris Kacerguis’ REST Server.
Problem:
The below code:
public function instamojotest_post()
{
$api = new Instamojo\Instamojo(‘abcd1234’, ‘efgh5678’, 'https://test.instamojo.com/api/1.1/');
try {
$response = $api->paymentRequestCreate([
'amount' => 100,
'purpose' => 'New Product Purchase',
'buyer_name' => 'Test User',
'email' => 'testuser#gmail.com',
'phone' => '9876543210',
'redirect_url' => 'http://www.example.com/products_api/validate_payment'
]);
header('Location: ' . $response['longurl']);
} catch (Exception $e) {
$this->response([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
is not redirecting to the Instamojo Payment Site and no error is being displayed.
It is working fine and redirecting successfully with vanilla CodeIgniter.
Questions:
1) Is it, at all, possible to redirect from within a REST Server Post Method?
2) If the above is possible, then what is wrong with my code?
3) Is there any other way to achieve what I am trying to do?
I found many tutorials on the internet but none of them are using REST Server.
I stumbled accross this question while Googling. I was also facing the same issue and here is how I solved it.
Note: This is not exactly a solution but a work-around. Also I admit that this may not be the best solution out there, but it worked for me.
I returned the payment url from the Rest Server, and redirected to the url from within the Rest Client.
Rest Client Code:
class Test extends CI_Controller
{
public function instamojo_make_payment()
{
$url = "http://www.example.com/products_api/instamojotest";
$params = []; //You will obviously be needing this in real life implementation :)
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($curl_handle);
curl_close($curl_handle);
if ($response['success'])
header('Location: ' . $response['payment_url']);
else
$this->load->view('payment_failed_page');
}
}
Rest Server Code:
class Products_api extends REST_Controller
{
public function instamojotest_post()
{
$api = new Instamojo\Instamojo('abcd1234', 'efgh5678', 'https://test.instamojo.com/api/1.1/');
try {
$response = $api->paymentRequestCreate([
//Make sure to pass these data from the Rest Client
'amount' => 100,
'purpose' => 'New Product Purchase',
'buyer_name' => 'Test User',
'email' => 'testuser#gmail.com',
'phone' => '9876543210',
'redirect_url' => 'http://www.example.com/products_api/validate_payment'
]);
$this->response([
'success' => true,
'payment_url' => $response['longurl']
], 200);
} catch (Exception $e) {
$this->response([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
}
While giving this answer I assumed that the Api is open. If it is not, then make sure to pass your credentials when making the curl call.
Update
Thanks to #AshwiniChaudhary's comment below, which states that:
REST APIs are not meant for redirection. REST API returns JSON, XML
etc and the receiver takes care of whatever is supposed to be done.
the actual reason behind the fact, "why REST Server is not letting us to perform the redirect", becomes pretty clear.

Yii2 AuthClient set return page for Facebook client

I have a form for lead gen, which just get the user information (like name, gender, email) which can be filled out with Facebook. But the problem is, selecting to fill form with FB redirect to index page. How can i set the return page to some other view or action?
public function onAuthSuccess($cliente)
{
// TODO: fb login e retornar dados do perfil para o form
$fb = new Facebook([
'app_id' => MYAPPID,
'app_secret' => MYAPPSECRET
]);
try {
$token = $cliente->getAccessToken()->getToken();
// Returns a `Facebook\FacebookResponse` object
$usuario = $fb->get('/me?fields=email,name,gender,age_range',
$token)->getDecodedBody();
} catch(Exception $e) {
echo 'Error: ' . $e->getMessage();
exit;
}
return ; // actually doesn't matter, it always end redirecting to site/index
}
Auth config:
'auth' => ['class' => yii\authclient\AuthAction::className(),'successCallback' => [$this, 'onAuthSuccess']]
Add successUrl in Auth action config
'successUrl'=>'url'
it is an public property you can override its value in your function also
$this->action->successUrl = "url-with-data";
Note: this is for understanding purpose only, best way to generate dynamic urls would be using urlmanager

Don't show 's3.amazon.com' when posting images to LinkedIn API

I am posting images to LinkedIn through the public api with my app that pulls the images from our S3 bucket. When the update appears on LinkedIn it shows 's3.amazon.com' next to the image. Is there any way that I can keep this from happening?
Ruby Code from app:
def post(message_body, attachment, post)
options = { :visibility => { :code => 'anyone' } }
if attachment.present?
options.merge!(:content => { :title => 'titles',
:description => 'descriptions',
:submitted_url => 'http://s3.amazonaws.com/...'
}, :comment => message_body)
else
options.merge!(:comment => message_body)
end
response = client.add_share(options)
post.posted!
JSON.parse(response.body)['updateUrl']
rescue LinkedIn::Errors::UnauthorizedError => e
raise SocialProfile::UnauthorizedError, e.message
rescue LinkedIn::Errors::AccessDeniedError => e
raise SocialProfile::UnauthorizedError, e.message
## Heading ##end

Sinatra + Paperclip; uploaded images have no extension

When uploading images Paperclip is saving files wo/ extensions. I'm using ActiveRecord
photo.rb (model):
require "sinatra"
class Photo < ActiveRecord::Base
include Paperclip::Glue
attr_accessible :image
has_attached_file :image,
:styles => {
:small => "100x100#",
:medium => "500x300"
},
:path => "#{settings.root}/public/system/:class/:attachment/:attachment/:id_partition/:style/:filename"
end
photos.rb (controller):
post "/photos/?" do
params[:photo][:image] = params[:photo][:image][:tempfile] if params[:photo][:image]
#photo = Photo.new(params[:photo])
if #photo.save
{ :status => "OK"}.to_json
else
{ :status => "NOK"}.to_json
end
end

ASIFormDataRequest to send post data to server rails, but in the insert have a null value

I'm using ASIFormDataRequest to send multipart POST data to a server rails.
The code snippet where I set the value with a text field and than send POST is below:
NSURL *url = [NSURL URLWithString:#"http://localhost:3000/users"];
ASIFormDataRequest *requestMsg = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[requestMsg setDelegate:self];
[requestMsg setPostValue:labelName.text forKey:#"name"];
[requestMsg startSynchronous];
In my rails log console I don't have any error and the post started correctly.
The problem is in the INSERT where the value of "name" is NULL:
Started POST "/users"
Parameters: {"name"=>"john"}
INSERT INTO "users" ("name", "created_at", "updated_at") VALUES (NULL, '2011-06-08 11:38:55.936498', '2011-06-08 11:38:55.936498')
Has anyone had this problem before?
This is the server side code
class UsersController < ApplicationController
# GET /users/new
def new
#user = User.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #user }
end
end
# POST /users
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
format.html { redirect_to(#user, :notice => 'User was successfully created.') }
format.xml { render :xml => #user, :status => :created, :location => #user }
else
format.html { render :action => "new" }
format.xml { render :xml => #user.errors, :status => :unprocessable_entity }
end
end
end
end
My ruby isn't strong so don't shoot me if this is wrong. But shouldn't the line:
#user = User.new(params[:user])
be
#user = User.new(params[:name])
?