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
Related
I have tried adding a new contact using Google People API with PHP client people service and it worked fine. I have used following code,
$service = new Google_Service_PeopleService($client);
$person = new Google_Service_PeopleService_Person();
$name = new Google_Service_PeopleService_Name();
$name->setGivenName($_name);
$person->setNames($name);
$phone1 = new Google_Service_PeopleService_PhoneNumber();
$phone1->setValue($_phone);
$phone1->setType('home');
$person->setPhoneNumbers($phone1);
$exe = $service->people->createContact($person)->execute;
Now I want to check if particular email already exists so tried searchContacts method of API. It works fine in API explorer.
ref:
https://developers.google.com/people/api/rest/v1/people/searchContacts
But when have tried with following code,
$service = new Google_Service_PeopleService($client);
$optParams = array('query'=>$_email,'pageSize' => 10, 'readMask' => 'emailAddresses', 'key'=>'XXXX');
try{
$rslt = $service->people->searchContacts($optParams);
} catch(Exception $ex) {
echo $e->getMessage();
}
i am getting following error,
PHP Fatal error: Call to undefined method Google_Service_PeopleService_Resource_People::searchContacts()
Looking at the error i am sure that the way to call the method is wrong. I have searched but not able to get proper documentation in guiding in that direction.
Any help will be appreciated.
Thanks
Looks like we cannot call searchContacts using people service object so i have used curl json to get it worked. I have used following code if anyone needs.
$url_parameters = array('query'=>$_email,'pageSize' => 10, 'readMask' => 'names,phoneNumbers,emailAddresses,organizations', 'key'=>'XXXXX');
$url_calendars = 'https://people.googleapis.com/v1/people:searchContacts?'. http_build_query($url_parameters);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_calendars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to search contact');
return $data;
Thanks
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);
I'm aware you can force update a page's cache by entering the URL on Facebook's debugger tool while been logged in as admin for that app/page:
https://developers.facebook.com/tools/debug
But what I need is a way to automatically call an API endpoint or something from our internal app whenever somebody from our Sales department updates the main image of one of our pages. It is not an option to ask thousands of sales people to login as an admin and manually update a page's cache whenever they update one of our item's description or image.
We can't afford to wait 24 hours for Facebook to update its cache because we're getting daily complaints from our clients whenever they don't see a change showing up as soon as we change it on our side.
Page metadata isn't the sort of thing that should change very often, but you can manually clear the cache by going to Facebook's Debug Tool and entering the URL you want to scrape
There's also an API for doing this, which works for any OG object:
curl -X POST \
-F "id={object-url OR object-id}" \
-F "scrape=true" \
-F "access_token={your access token}" \
"https://graph.facebook.com"
An access_token is now required. This can be an app or page access_token; no user authentication is required.
If you'd like to do this in PHP in a with-out waiting for a reply, the following function will do this:
//Provide a URL in $url to empty the OG cache
function clear_open_graph_cache($url, $token) {
$vars = array('id' => $url, 'scrape' => 'true', 'access_token' => $token);
$body = http_build_query($vars);
$fp = fsockopen('ssl://graph.facebook.com', 443);
fwrite($fp, "POST / HTTP/1.1\r\n");
fwrite($fp, "Host: graph.facebook.com\r\n");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($fp, "Content-Length: ".strlen($body)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");
fwrite($fp, $body);
fclose($fp);
}
If you're using the javascript sdk, the version of this you'd want to use is
FB.api('https://graph.facebook.com/', 'post', {
id: [your-updated-or-new-link],
scrape: true
}, function(response) {
//console.log('rescrape!',response);
});
I happen to like promises, so an alternate version using jQuery Deferreds might be
function scrapeLink(url){
var masterdfd = $.Deferred();
FB.api('https://graph.facebook.com/', 'post', {
id: [your-updated-or-new-link],
scrape: true
}, function(response) {
if(!response || response.error){
masterdfd.reject(response);
}else{
masterdfd.resolve(response);
}
});
return masterdfd;
}
then:
scrapeLink([SOME-URL]).done(function(){
//now the link should be scraped/rescraped and ready to use
});
Note that the scraper can take varying amounts of time to complete, so no guarantees that it will be quick. Nor do I know what Facebook thinks about repeated or automated usages of this method, so it probably pays to be judicious and conservative about using it.
This is a simple ajax implementation. Put this on any page you want facebook to scrape immediately;
var url= "your url here";
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com?id='+url+'&scrape=true',
success: function(data){
console.log(data);
}
});
An alternative solution from within a Drupal node update using curl could be something like this :
<?php
function your_module_node_postsave($node) {
if($node->type == 'your_type') {
$url = url('node/'.$node->nid,array('absolute' => TRUE));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v1.0/?id='. urlencode($url). '&scrape=true');
$auth_header = 'Oauth yOUR-ACCESS-TOKEn';
curl_setopt($ch, CURLOPT_HTTPHEADER, array($auth_header));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$r = curl_exec($ch);
curl_close ($ch);
}
}
Notice the hook_node_postsave() implementation which is not standard Drupal core supported.
I had to use www.drupal.org/project/hook_post_action in order to get this facebook scrape pickup last made changes to the node, since hook_node_update() is not triggered after databases have been updated.
Facebook requires now the access token in order to get this done.
Guidelines to acquire a token can be found here :
https://smashballoon.com/custom-facebook-feed/access-token/
I'm the author of Facebook Object Debugger CLI, a command-line interface written in PHP, aim to refresh the Facebook cache for a single URL or a bunch of URLS using as input a text file. The package is also available on Packagist and can be installed using Composer.
There are changes in Graph API v2.10:
When making a GET request against a URL we haven't scraped before, we will also omit the og_object field. To trigger a scrape and populate the og_object, issue a POST /{url}?scrape=true. Once scraped, the og_object will remain cached and returned on all future read requests.
We will require an access token for these requests in all versions of the Graph API beginning October 16, 2017.
Source: Introducing Graph API v2.10
So now we should use POST-method for scraping:
POST /{url}?scrape=true
Not
A solution with the PHP Facebook SDK:
<?php
try {
$params = [
'id' => 'https://www.mysitetoscrape.com/page',
'scrape' => 'true',
];
$response = $fb->post('/', $params);
print_r($response);
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
?>
Here's my Ruby solution using Koala gem and Facebook API v2.9
api = Koala::Facebook::API.new(access_token)
response = api.put_object(nil, nil, {scrape: true, id: "url-of-page-to-scrape"})
response should be a hash of attributes retrieved from the og: meta tags on the page which was scraped.
I was facing this same problem.
There is a simple way to clear cache.
http://developers.facebook.com/tools/debug
Enter the URL following by fbrefresh=CAN_BE_ANYTHING
Examples: http://www.example.com?fbrefresh=CAN_BE_ANYTHING
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 .
I have a web service that works fine with get requests but trying to use post it doesn't seem to work. I have this in my routes:
Router::connect("/products/service_add", array("controller"=>"products", "action" => "service_add", 'seller'=>true, "[method]" => "POST"));
Seller is like an admin. I also have ParseExtensions('xml'). My action is:
function seller_service_add() {
$this->log("hit", 'debug');
$hi = array("message"=>"hey");
$this->set(compact('hi'));
}
and the view is:
<product>
<?php echo $xml->serialize($hi); ?>
</product>
When I try to send a post to the API I just get a debug trace back with timer info. In the same script as I'm doing the post request I'm doing a get and when I run the script I can see the data passed by the API for the get but not for the post request.
The code I'm using to send the post is:
$ch = curl_init();
$data = array('Your' => 'Data');
curl_setopt($ch, CURLOPT_URL, "http://localhost/<project>/products/service_add.xml");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);`
Any ideas on why this isn't working? Any help would be much appreciated.
Sorry if this is a bit verbose!
Update: I've added lines to spit stuff out to the cakephp debug log when actions are hit. I have one entry on the beforeFilter, this entry gets hit and I can see it in the log. The entry in the service_add action is not present in the log so I guess that the action is not being hit?
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
shouldn't this line be
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);