Send data from drupal form to Web service Client (REST) - web-services

I create a simple form. When I put data in all fields of the form and press a submit button, then all data that were completed on the form should be sent to a Web service client (rest).
My question is, how to send all data from my form to web service? Is there a module for that or I have to draw on an API?
Thanks :D
UPDATE:
I created my form that contains 2 fields: "Name" and "Phone" and a submit button. (All in my own module)
Then I show my code that I just did. However, when I see the web service. The shipping data, not shown. I did a debug and uh I realized that when running: "curl_exec ($ch)" returns me FALSE.
function mymodule_form_submit($form, &$form_state){
$name = $form_state['values']['name'];
$phone = $form_state['values']['phone'];
$data = array(
'name' => $name,
'phone' => $phone
);
$url = 'http://[IP]/event/management/attendee';
$headers = array('Content-Type: multipart/form-data');
$userpasswd = 'user:pass';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_USERPWD, $userpasswd);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$result = curl_exec($ch);
curl_close($ch);
}
The params,in the web service, are: attendee['name'], attendee['phone']. What is my error?

Sure man try the service module 3 . It's one of drupal great module as usual .
here's the link ( http://drupal.org/node/736522 ) , you can also authenticate user before getting the fields by using two techniques either session authentication or aouth authentication .. you can call your drupal from client application by one of those approach "json,xml-rpc, rest".
1- first the session authentication takes a user name and password and authenticates. Then it takes the user permissions from drupal so you need to authenticate in each step to go through your application that communicate with your drupal. Anonymous users can get what they want according to your permission in drupal.
2- While in Aouth authentication you create a user and add token to him and only the user who had the token communicate with the application according to the permission rule you set to him . In case of anonymous users they can't retrieve or get anything. The communication between drupal and the client within the created used with a certain token.
Feel free to contact me for more support.

sorry for miss-understanding .
there's two implementation method to do this :
1- You may do a custom module which hooks on the node_api and on submit form get posted data and send it to webservice by this method
$json = drupal_http_request('http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false');
$decode = json_decode($json->data, TRUE);
or by using this module web service client module ( http://drupal.org/project/wsclient ) this is only for drupal 7
2- and this is a guide about this module http://drupal.org/node/1114308 .

Related

Service account API error when getting the access token

I am testing google people API for our web application.
Steps:
I created new project in the google console (https://console.cloud.google.com/)
I enabled People API
I created needed Credentials - web client for my application and API key
I created service account with p12 key for server to server queries and enabled "Google Workspace Domain-wide Delegation"
I configured OAuth consent screen with scopes needed to authorize to google and get access to people API: /auth/userinfo.email /auth/userinfo.profile /auth/contacts /auth/contacts.readonly
Then my PHP script using "Google API PHP client" make redirect link to consent screen and return code for access token with Web client:
<?php
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('My Project xxxxx');
$client->setClientId('999999999999-qwertysdfhwe9uriiiiiiiiiiiiiiiii.apps.googleusercontent.com');
$client->setClientSecret('GOCSPX-hhhhhhhhhhhhhhhhhhhhhhhhhhhh');
$client->setDeveloperKey('AIzafffffffffffffffffffffffffffffffffff'); // API key
$client->setState('subdomain.myapp.com');
$scriptUri = 'https://oauth.myapp.com/auth.php';
$client->setRedirectUri($scriptUri);
$client->addScope('https://www.googleapis.com/auth/userinfo.email');
$client->addScope('https://www.googleapis.com/auth/userinfo.profile');
$client->addScope('https://www.googleapis.com/auth/contacts');
$auth_url = $client->createAuthUrl();
header('Location: '.$auth_url);
?>
This code redirects to google Authentication screen, then I login with google and approve scopes. Google redirects me back to my app and now I have access token and aproved scopes and email of authenticated user.
The next step I have huge trouble - server - to - server query to get access token for people API
function base64_url_encode($input) {
return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
}
$iat = time();
$url = "https://www.googleapis.com/oauth2/v4/token";
$scope = 'https://www.googleapis.com/auth/contacts';
$jwt_data = array(
'iss' => '111111111111111111111', // My service account ID
'aud' => $url,
'scope' => $scope,
'exp' => $iat + 3600,
'iat' => $iat,
'sub' => 'user#gmail.com', // Email of the user that was autenticated in first step
);
openssl_pkcs12_read(file_get_contents('keyfile.p12'), $certs, 'notasecret');
$header = array('typ' => 'JWT', 'alg' => 'RS256');
$signing_input = base64_url_encode(json_encode($header)) . '.' . base64_url_encode(json_encode($jwt_data));
openssl_sign($signing_input, $signature, $certs['pkey'], 'SHA256');
$jwt = $signing_input . '.' . base64_url_encode($signature);
$data = array(
"grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion" => $jwt
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
curl_close($ch);
$google_contacts_api_tokens_collection[$use_mailbox] = $response;
return $response;
And this code google returns the error that I can not fix, and I have no any ideas.
The text of error:
"Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."
Your code is trying to impersonate a user via a service account. This requires enabling Domain Wide Delegation. In a round-about way, the error message means the service account does not have permission because delegation is not enabled.
Perform Google Workspace Domain-Wide Delegation of Authority
If the user is not part of Google Workspace, then you cannot impersonate the user.
Yes, but I already tried this and it does not help. I configured scopes for service account in the Google Workspace, and also checked the "Enable Google Workspace Domain-wide Delegation" checkbox in google console. In Google Workspace I used digital Client ID of my service account.
And also I discovered one strange moment:
Web client always returns good access token, but when I request service account access token it works well only for google console project owner ('sub' => 'project.owner#gmail.com'). And if I request service account access token for another user ('sub' => 'project.testuser#gmail.com') Google also returns the same error: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.

Making a call to my webservice via curl doesn't work

I have a simple function to test my webservice via POST like this:
function service(){
$service_url = 'http://example.com/example_endpoint/user';
$curl = curl_init($service_url);
$header = array(
'Content-Type: application/x-www-form-urlencoded'
);
$curl_post_data = array(
"name" => "name_test",
"mail" => "name_test#example.com",
"pass" => "123",
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
$curl_response = curl_exec($curl);
curl_close($curl);
$xml = new SimpleXMLElement($curl_response);
}
The webservice is specting the parameters on the array and the Content-Type is suppoused to be application/x-www-form-urlencoded but when I run the function in my browser and check the "Network" tab on "inspect element", there is a call to my webservice via GET despite of the fact that I'm setting the option to be POST
and the Content-Type keeps on text/html
This webservice allows to create users with the parameters inside the array $curl_post_data
I use the add-on "Poster" on Mozilla to call my webservice and it's succesfull, but when I call the function above, it doesn't work ¿How could I implement this function to make the correct call?
In Network tab on your browser you will not see POST as curl is posting this. Network tab shows activity from client side (Browser). Your data posting is happening by server through CURL.
Add this code to properly url encode data
$curl_post_data_string = '';
//url-ify the data for the POST
foreach($curl_post_data as $key => $value) {
$curl_post_data_string .= $key.'='.$value.'&';
}
rtrim($curl_post_data_string, '&');
And change this line
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
Keep in mind to see what you got after hitting a URL in CURL you need to print $curl_response
echo $curl_response;
This is a proper example of posting data using CURL
http://davidwalsh.name/curl-post

How To Post Notification As Application

How to post a notification to users as application using facebook php sdk?
I have attached an image, in that picture we can see application from SongPop post a notification to me. I want to make something like this. I think this app post notification to their users, can I post a notification to a spesific user?
you have to a canvas page url set to in your app config then try with this code
$url = "https://graph.facebook.com/$user_id/notifications";
$notification_message = 'My Example Notification Message';
$app_access_token = $app_id . '|' . $app_secret;
$attachment = array(
'access_token' => $app_access_token, // access_token is a combination of the AppID & AppSecret combined
'href' => '', // Link within your Facebook App to be displayed when a user click on the notification
'template' => $notification_message, // Message to be displayed within the notification
);
// set the target url
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$result = curl_exec($ch);
curl_close ($ch);

Publish on facebook fan page when the user is not logged-in

I'm using the Graph API code that uses an acces_token and an id_page with permissions to post to a fan page. It works as long as the user is logged, but when I log out the access_token expires and I can't publish to fan page.
How can I make my application to be able to publish at any time, even when the user is not logged in?
This is my code:
<?php
$page_access_token = 'AAAFNxxxx';
$page_id = '15203xxx';
$data['picture'] = "https://www.google.it/logos/2012/moby_dick12-hp.jpg";
$data['link'] = "http://www.google.it/";
$data['message'] = "Test";
$data['description'] = "Lorem ipsum dolor sit amet";
$data['access_token'] = $page_access_token;
//curl connection
$post_url = 'https://graph.facebook.com/'.$page_id.'/feed';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch); ?>
You can use extended token to post when the user has logged out, by retrieving the same exchanging you own client_id (your app_id), your app_secret, and the non-expired, short-lived access_token
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
Make pending posts in your word press blog, connect your blog with networkbloggers and fanpage.So it will be: Your awaesome WP + Networkbloggers = post on Facebook Fanpage
That must work i'm using it long time every time my post enter on my facebook fan page no need app. or something more complicate

create events on my Application's page

I am in a process of writing an app which works this way
1. Asks a user permission for events_create, publish_stream
2. Gets the access_token for the same
3. takes input of Title, date, time, location( ie all inputs) from a form and then calls graph api like
/$app_id/events along with access token and post date
I want this to create an event within my APPLICATION's events and hence I use $app_id instead of ..../me/events
But it creates an event on USER's wall ???
I want users to be able to create an event on my wall. It should be an event whose owner is the application and the user should get invited along with his contacts( if he chooses so) ...
Basically, I think POST to /$app_id/events and /me/events work the same, I think it should not ... Am I missing something?
Thanks in advance ..
AC
HiShakyeb,
Same result ... It just creates an event in my account rather than the application's.
Here is the code I am using ..
$url = "https://graph.facebook.com/$app/events?" . $access_token;
$params = array();
// Prepare Event fields
foreach($_POST as $key=>$value)
if(strlen($value))
$params[$key] = $value;
$params['name']=mysql_real_escape_string($params['name']);
$params['description']=mysql_real_escape_string($params['description']);
$params['location']=mysql_real_escape_string($params['location']);
$params['end_time']=date('Y-m-d H:i:s', mktime(0, 0, 0, date("m") , date("d")+1, date("Y")));
$params['privacy_type']="SECRET";
// Start the Graph API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
$decoded = json_decode($result, true);
curl_close($ch);
I also tried just app/events? instead of $app/events?
Thanks a lot ...
Use a Page Admin access token to take an action on behalf of that application's page. To do this, get /me/accounts with the manage_pages permission. That will give you the pages you have access to (including the app's profile page), along with an access token to use for acting as that page/application. If you use that access token, then events will be created as the application page and not the user. See the Graph API documentation for the Page object for more details.
With PHP-SDK I uses the api call for automatic POSTING an Event in App page after filling a form.
Here the automatic process after the user (You) have an valid APP access_token and manage app/page permissions. The token to use is your APP token you receive with your FBapp connection.
Starting creating php-sdk object
$connectparam = array();
$connectparam['appId'] = 'YOURAPPID';
$connectparam['secret'] = 'YOURAPPSECRET';
$connectparam['fileUpload'] = 'true';
$connectparam['cookie'] = 'true';
$facebook = new Facebook($this->connectparam);
Building the event informations
$FBcreateAnTestEvent = array();
$nowtime = date('Y-m-d H:i:s');
$FBcreateAnTestEvent['name'] = 'Test Event in myApp from me';
$FBcreateAnTestEvent['start_time'] = $nowtime;
$FBcreateAnTestEvent['privacy_type'] = 'SECRET';
$FBcreateAnTestEvent['description'] = 'This Event is created from my WebFBApp and is a testing Event creating by Qtronik from myWebApp';
Automaticly create event
$resp = '<a href="'.$facebook->api('/me/events','POST',$FBcreateAnTestEvent).'">
Create a test event</a>';
echo $resp;
When is echoing the php-sdk create immediately the Event so it's better to put it in a ajax or in action linked page in a form
For FanPage use FQL link
If You parse the FBuser admin_pages and filter by APPLICATION field and/or filter by your FBpage id you can get this user FBpages admin access_token's. Of Course you need the manage_pages permissions. Then you need admin_events permission to publish to FBfanPage's. I create an FanPageEvent with GraphApi link like this:
$pageAccessToken = $facebook->api('/' . $YOURPAGEID . '/?fields=access_token');
$resp = '<a href="https://graph.facebook.com/'.$pageAccessToken['id'].'/events
?access_token=' . $pageAccessToken['access_token'] . '
&method=POST
&name='.$FBcreateAnTestEvent['name'].'
&start_time='.$FBcreateAnTestEvent['start_time'].'
&location='.$FBcreateAnTestEvent['location'].')">
Create a test event</a>';
Then voila I have allot of other things to do with this for handle it with Ajax but this is the two way of adding an Event's to Facebook from a website administrating way... All this it's not very intended for personal profile event create so it's more difficult to spam FBpages and or FBapp/FBwebapp.
I'm French speaking so excuse my poor English... ;)