Need to Implement Zend_Rest_Client for the following curl method - php

I usually use curl to call rest api's like this
$user_data = array("userName" => "myuser#mydomain.com" ,"password" => "mydomain123" );
$data = json_encode($user_data);
$headers = array('Accept: application/json', 'Content-Type: application/json',);
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, 'http://myursl.com/myapi/v1/Api.svc/something/someother');
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
print_r($response);
The above code is working fine with API and printing the expected response , When I do the same thing using Zend_Rest_client of Zend Framework
like this
$base_url = 'http://myursl.com/myapi/v1_0/Api.svc';
$endpoint = '/something/someother';
$user_data = array("userName" => "myuser#mydomain.com" ,"password" => "mydomain123" );
$client = new Zend_Rest_Client($base_url);
$response = $client->restPost($endpoint, $user_data);
I am getting 404 error like this
(Zend_Http_Response)#62 (5) { ["version":protected]=> string(3) "1.1" ["code":protected]=> int(404) ["message":protected]=> string(9) "Not Found"] }
Where actually I am wrong in implementing Zend Rest Client
Thanks in advance for responding to this post

Although it might not be the finest solution I finally ended up inheriting Zend_Rest_Client and overriding _performPost() like this:
class My_Rest_Client extends Zend_Rest_Client {
protected function _performPost($method, $data = null)
{
$client = self::getHttpClient();
if (is_string($data)) {
$client->setRawData($data, 'application/json');
} elseif (is_array($data) || is_object($data)) {
$client->setParameterPost((array) $data);
}
return $client->request($method);
}
}
And then:
$rest = new My_Rest_Client('http://my.rest.url');
$rest->restPost('post-path', $data);

Related

curl_exec($handle) returns nothing

I'm building a simple CRUD API in PHP and Curl and I have an HTML form that sends ID, FName, LName.
The form is posted to create.php and then calls ApiHandler.php that set up the Curl request, then send it to read-api.php.
The json file is updated with the new user and returns the json file content as a string but $response is an empty string and doesn't contain the json content
$response = curl_exec($handle); // $response = ""
ApiHandler.php
<?php
function callAPI($method, $url, $request){
$handle = curl_init();
switch ($method){
case "GET":
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
break;
case "PUT":
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "PUT");
if ($request)
curl_setopt($handle, CURLOPT_POSTFIELDS, $request);
break;
case "POST":
curl_setopt($handle, CURLOPT_POST, 1);
if ($request)
curl_setopt($handle, CURLOPT_POSTFIELDS, $request);
break;
case "DELETE":
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "DELETE");
default:
if ($request)
$handle = sprintf("%s?%s", $url, http_build_query($request));
}
curl_setopt($handle, CURLOPT_HTTPHEADER, [
"Content-Type: application/json; charset=UTF-8",
"Access-Control-Allow-Origin: *"
]);
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($handle); // $response = ""??
$errno = curl_errno($handle);
$err = curl_error($handle);
curl_close($handle);
if ($errno) {
return "cURL Error #:" . $err;}
else {
return $response;
}
}
function getBaseUrl()
{
return "http://localhost/api/";
}
?>
This is the api that take the request and supposed to save it to a file and return the json string.
create-api.php
<?php
include('ApiHandler.php');
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$postData = file_get_contents('php://input');
$data = array();
parse_str($postData, $data);
$json = file_get_contents('employees.json');
$obj = json_decode($postData,true);
$jsonarray = json_decode($json,true);
array_push($jsonarray,$obj);
$result = json_encode($jsonarray);
$file = fopen('employees.json','w');
fwrite($file,$result);
fclose($file);
return $result;
?>
create.php
<?php
include('ApiHandler.php');
$url = getBaseUrl()."create-api.php";
$postdata = file_get_contents("php://input");
$id = $_REQUEST["id"];
$firstname = $_REQUEST["firstname"];
$lastname = $_REQUEST["lastname"];
$arrayRequest = array("id"=>$id,"firstname"=>$firstname,"lastname"=>$lastname);
$json = json_encode($arrayRequest,true);
$output = callAPI("POST", $url, $json);
var_dump($output);
echo ("<p>$output</p>");
?>
Does anyone have any idea why the response is empty?
Your create-api.php script needs to output something to be caught by curl_exec()
So you need to replace your return $result; (which makes no sense in this context as you are not in a function) by echo $result;
Try to change this line in your code from:
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
to this:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true)

Wowza Cloud API: curl requests

I can't make it work.. :( I have this function (for create passthrough transcoder), when I run I see NULL in the web. If I test directly from the browser with the url, it does notify me that there is a problem an auth (apikey and acceskey)
function createPassthrough($name, $source_url, $recording = null)
{
$url = "https://sandbox.cloud.wowza.com/api/v1/transcoders";
$json = '{
"transcoder":{
"billing_mode":"pay_as_you_go",
"broadcast_location":"eu_belgium",
"delivery_method":"pull",
"name":"prueba",
"protocol":"rtsp",
"source_url":"url_camara",
"transcoder_Type":"passthrough",
"low_latency":true,
"buffer_size":0,
"play_maximum_connections":100,
"stream_smoother":false
}
}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json; charset=utf-8',
'Content-Type: application/json; charset=utf-8',
'wsc-api-key:' . $apiKey,
'wsc-access-key:' . $accessKey,
));
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
var_dump($obj);
}
What am I doing wrong? Thanks in advance.
You should check for curl errors after $result = curl_exec($ch);.
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}

LinkedIn API - Couldn't parse share document - Json

So i'm working with the LinkedIn API and i'm trying to share something to my wall but i'm getting the following error:
Couldn't parse share document: error: Unexpected end of file after null
I think something is going wrong with with adding the HTTPHEADERS:
Content-Type: application/json
x-li-format: json
So this is what i'm trying to do:
$parameters = array("comment" => "Check out developer.linkedin.com, I'm currently testing it myself!",
"content" => array( "title" => "LinkedIn Developers Resources",
"description" => "Leverage LinkedIn's APIs to maximize engagement",
"submitted-url" => "https://developer.linkedin.com",
"ubmitted-image-url" => "https://example.com/logo.png"
),
"visibility" => array("visibility" => "anyone")
);
$result = $connection->post("people/~/shares", $parameters);
var_dump($result);
var_dump($result); shows the error message above.
And these are the functions i'm using:
public function post($path, $parameters = []){
$url = $this->createUrl($path);
$parameters = json_encode($parameters);
return $this->curlRequest('POST', $url, $parameters);
}
this is the post function, wich is using the following functions:
private function createUrl($path) {
return self::API_HOST . "/v" . self::API_VERSION . "/" . $path . "?" . self::FORMAT;
}
private function curlRequest($method, $url, $postData = NULL, $accessToken = false){
$curl = curl_init();
switch($method) {
case 'GET':
break;
case 'POST':
curl_setopt($curl, CURLOPT_POST, true);
if($accessToken) {
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postData));
} else {
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
}
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'x-li-format: json'));
break;
}
if ($accessToken) {
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
} else {
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $this->accessToken));
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $url);
$result = curl_exec($curl);
curl_close($curl);
return json_decode($result, true);
}
Hope someone can help me with this problem.

Airbnb Login Script through the command line using PHP

Is there a way to programmatically login to Airbnb with email/password through a CLI PHP script? and get a response back?
Thanks.
If you're looking to remotely log in to Airbnb and return information, you can use cURL to post data to Airbnb and return the results.
Examples on how to post form data can be found all over the web, however, a very reputable tutorial can be found here. Essentially, you want to cURL the login page, and include the login information with POST.
<?php
// A very simple PHP example that sends a HTTP POST to a remote site
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.airbnb.com/login");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"email=" . $email . "&password=" . $password);
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('email' => $email, 'password' => $password)));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
Make sure you check out this answer on SO, as well as the tutorials here.
Yes, there is. Airbnb's API isn't open to the general public, but if you sniff the traffic from your phone, you can see what requests are being sent to which endpoints. I experimented a little bit with their API and it follows as such for logging in
<?php
class AirBnB {
// Define the properties
public $currency = 'USD';
public $language = 'en';
public $country = 'us';
public $network = 'AT&T';
public $apiKey = '915pw2pnf4h1aiguhph5gc5b2';
public $adId = '911EBF1C-7C1D-46D5-A925-2F49ED064C92';
public $deviceId = 'a382581f36f1635a78f3d688bf0f99d85ec7e21f';
public function SendRequest($endpoint, $token, $post, $data, $cookies) {
$headers = array(
'Host: api.airbnb.com',
'Accept: application/json',
'Accept-Language: en-us',
'Connection: keep-alive',
'Content-Type: application/json',
'Proxy-Connection: keep-alive',
'X-Airbnb-Carrier-Country: '.$this->country,
'X-Airbnb-Currency: '.$this->currency,
'X-Airbnb-Locale: '.$this->language,
'X-Airbnb-Carrier-Name: '.$this->network,
'X-Airbnb-Network-Type: wifi',
'X-Airbnb-API-Key: '.$this->apiKey,
'X-Airbnb-Device-ID: '.$this->deviceId,
'X-Airbnb-Advertising-ID: '.$this->adId,
);
// Add the new custom headers
if($token) {
$header = 'X-Airbnb-OAuth-Token: '.$token;
array_push($headers, $header);
}
// Add the query string
if(!$post && is_array($data)) {
$endpoint .= '?'.http_build_query($data);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.airbnb.com/'.$endpoint);
curl_setopt($ch, CURLOPT_USERAGENT, 'Airbnb/15.50 iPhone/9.2 Type/Phone');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if($post) {
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
if($cookies) {
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
} else {
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
}
$response = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array(
'http' => $http,
'response' => $response
);
}
public function Authorize($username, $password) {
$data = array(
'username' => $username,
'password' => $password,
'prevent_account_creation' => TRUE,
);
$data = $this->SendRequest('v1/authorize', FALSE, TRUE, $data, FALSE);
if($data['http'] == 200) {
$json = #json_decode($data['response'], TRUE);
return $json['access_token'];
} else {
return FALSE;
}
}
}
// Call a new instance of AirBnB
$airbnb = new AirBnB;
// Get the OAuth token
$token = $airbnb->Authorize('my#email.com', 'password');
?>
You can find out more about their API here.

twitter api update status updating but no response from twitter

having a bit of an issue with the twitter API. When I send something to https://api.twitter.com/1/statuses/update.json, the tweet (status update) does get sent, however, I do not get a response from twitter. When I send requests to any of the other api urls they work as expected and do return a response. Please see code below...
function postStatus($oauthToken,$status) {
//Create sig base string
$tokenddata = array('oauth_token'=>$oauthToken['oauth_token'],'oauth_token_secret'=>$oauthToken['oauth_token_secret']);
$status = rawurlencode($status);
$baseurl = $this->baseurl . "statuses/update.json";
$url = "{$baseurl}?status={$status}";
$authHeader = get_auth_header($url, $this->_consumer['key'], $this->_consumer['secret'],
$tokenddata, 'POST', $this->_consumer['algorithm']);
$postfields = "status={$status}";
$response = $this->_connect($url,$authHeader,$postfields,'POST');
return json_decode($response);
}
private function _connect($url, $auth, $postfields=null, $method='GET') {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($ch, CURLOPT_SSLVERSION,3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($auth));
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, TRUE);
if (!empty($postfields)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
}
}
$curl_info = curl_getinfo($ch);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
And as I said before, the other requests that I am using are 'GET' requests and use the code below...
function getFromTwitter($url, $oauthToken, $params=null) {
$tokenddata = array('oauth_token'=>$oauthToken['oauth_token'],'oauth_token_secret'=>$oauthToken['oauth_token_secret']);
$baseurl = $this->baseurl . $url;
if(!empty($params)) {
$fullurl = $baseurl . "?" . build_http_query($params);
$postfields = build_http_query($params);
$authHeader = get_auth_header($fullurl, $this->_consumer['key'], $this->_consumer['secret'],
$tokenddata, 'GET', $this->_consumer['algorithm']);
} else {
$authHeader = get_auth_header($baseurl, $this->_consumer['key'], $this->_consumer['secret'],
$tokenddata, 'GET', $this->_consumer['algorithm']);
}
if(!empty($postfields)) {
$response = $this->_connect($fullurl,$authHeader);
} else {
$response = $this->_connect($baseurl,$authHeader);
}
return json_decode($response);
}
Thanks for all of the help!
-SM
Implementing code for social networks on your own can be a pain (in my opinion)
It would be easier for you to use twitter-async (https://github.com/jmathai/twitter-async)
I have added it before to my CI as a helper function then used it as is.
It was easy to use & well documented.

Categories