how to request addDelegates ? 415 error - php

may I need to access to the emailsettings api with POST action in php.
But i always get this error :
failed to open stream: HTTP request failed! HTTP/1.0 415 Unsupported Media Type
Here is my code:
public function addDelegates($account,$delegates,$domain,$tokken) {
foreach ($delegates as $key => $value) {
sleep(5);
$url = "https://apps-apis.google.com/a/feeds/emailsettings/2.0/".$domain."/".$account."/delegation";
$requestXML = '<?xml version="1.0" encoding="utf-8"?>
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006">
<apps:property name="address" value="' . $value . '" />
</atom:entry>';
$requestHeaders = array(
'Content-type: application/xml+atom',
'Accept: application/xml+atom',
sprintf('Content-Length: %d', strlen($requestXML))
);
$context = stream_context_create(
array(
'http' => array(
'method' => 'POST',
'header' => implode("\r\n", $requestHeaders),
'content' => $requestXML,
)
)
);
$responseXML = file_get_contents($url, false, $context);
}
I saw that this error means that i may send wrong content type. But i tried application/json, application/xml, text/xml etc..
Nothing is precised about what data we have to send in emailSettings api doc :/
Thanks in advance .

I think content type in your posted code is not correct. change content-type to "application/atom+xml" instead of application/xml+atom. This should resolve your 415 error.

Related

Registration in Notification Hub with PHP Backend

For user requeriments the backend must be PHP and the app client is in Ionic 2. Based on:
https://msdn.microsoft.com/en-us/library/azure/dn223265.aspx
https://github.com/Azure/azure-notificationhubs-samples/tree/master/notificationhubs-rest-php
https://github.com/webwarejp/notificationhubs-rest-php
Create Registration Notification Hub Azure PHP Important
I created this method in php API:
$uri = $this->endpoint . $this->hubPath . "/registrations".NotificationHub::API_VERSION;
/* print($uri); */
$ch = curl_init($uri);
$token = $this->generateSasToken($uri);
$headers = [
'Authorization: '. $token,
'Content-Type: '."application/atom+xml;type=entry;charset=utf-8",
'x-ms-version: 2015-01',
'Content-Length: 0'
];
$body = $this->getXmlAndroid($registrationId, $tag);
print_r($body);
curl_setopt_array($ch, array(
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $body
));
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
print_r(curl_error($ch));
throw new Exception(curl_error($ch));
}
$info = curl_getinfo($ch);
print_r($info);
curl_close($ch);
The getXmlAndroid method is simple return xml format with GCM ID
private function getXmlAndroid($registrationId){
return '<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<content type="application/xml">
<GcmRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
<GcmRegistrationId>'.$registrationId.'</GcmRegistrationId>
</GcmRegistrationDescription>
</content>
</entry>';
}
I get the GcmRegistrationId with this function in Ionic 2 app.
import { Push, PushObject, PushOptions } from '#ionic-native/push';
....
const options: PushOptions = {
android: { senderID: 'MyIDFirebaseProject'},
ios: { alert: 'true', badge: true, sound: 'false'},
windows: {}
};
pushObject.on('registration').subscribe((registration: any) => {
console.log(registration.registrationId);
});
The problem is always request to Registration method in Notification API return
[http_code] => 400
Where 400 means the "Invalid request body. The registration could not be created because the request was malformed.". I don't understand why this happen.
Why you send Content-Length: 0 header? It may cause a problem.

PHP to connect to remote Parse MongoDB; cURL works on command line but PHP file_get_contents doesn't

I am working with a Wordpress site with CPanel and a MySQL database. I want to be able to read data from a MongoDB held on Parse.com. Eventually, I want to change Wordpress's login.php script to search through the MongoDB and create users if necessary.
I am having lots of trouble connecting to the database.
Here is my php script:
<?php
$url = 'http://mercury.example.com:2234/parse/login';
$data = array('username' => 'username', 'password' => 'password');
$appID = "X-Parse-Application-Id: parseAppID";
$restKey = "X-Parse-REST-API-Key: praseRESTapiKey";
$session = "X-Parse-Revocable-Session: 1";
$contentType = "Content-Type: application/json";
$context = array(
'http'=> array(
"method" => "GET",
"header" => $appID . $restKey . $session . $contentType,
"content" => http_build_query($data)));
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
var_dump($result);
?>
The errors I am receiving are:
Notice: file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded in C:\wamp\www\parseDB.php on line 26
Warning: file_get_contents(http://mercury.example.com:2234/parse/login): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in C:\wamp\www\parseDB.php on line 26
From my understanding, the 403 error means the web server is returning the "forbidden" status code.
I am testing my php script on localhost using WAMP. A colleague of mine tried to run a similar command on Bash and received a response. (I broke it out so it is easier to read).
curl -X GET
-H "X-Parse-Application-Id: parseAppID"
-H "X-Parse-REST-API-Key: parseRESTapiKey"
-H "X-Parse-Revocable-Session: 1"
-G --data-urlencode 'username=username' --data-urlencode 'password=password'
http://mercury.example.com:2234/parse/login
I have been stuck on this for 2 days so far, and I have no idea what is going on. I appreciate all the help I can get.
EDIT
Here is my final solution:
$url = 'http://mercury.example.com:3432/parse/login';
$data = array('username' => 'USERNAME', 'password' => 'PASSWORD!');
$context = array(
'http'=> array(
'method' => "GET",
'header' => "X-Parse-Application-Id: APPID\r\n" .
"X-Parse-REST-API-Key: RESTAPIKEY\r\n" .
"X-Parse-Revocable-Session: 1" .
"Content-Type: application/json\r\n",
'content' => http_build_query($data)
)
);
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
var_dump($result);
?>
Look at the stream_content_create example at http://php.net/manual/en/function.stream-context-create.php which explains how to pass headers properly. At this time, you slam each header together without any line feeds which will make them look like concatenated string:
X-Parse-Application-Id: parseAppIDX-Parse-REST-API-Key: praseRESTapiKeyX-Parse-Revocable-Session: 1Content-Type: application/json
Hint - add \r\n after each header line.
Instead of file_get_contents you could also use curl methods.

PHP post request returns 400 error

I have the following class, it's using a web service to send a request and get a JSON response back.
When i try the same thing with Chrome's Postman extension, I get a nice little response back.
class RequestController {
function __construct() {
global $config;
$this->config = $config;
}
function send_request() {
$url = $this->config['GATEWAY']['url'] . 'getbyquery';
$json_data = '{"query":{"AllFields":true,"ConditionSetOperator":0,"ConditionSets":[],"Distinct":false,"Fields":["jay_alb","jay_levelms"],"Links":[],"Orders":[],"RecordType":"jay_lifeinsurance","Top":0}}';
$data = array($json_data);
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
print "<pre>";
print_r($options);
print "</pre>";
$result = file_get_contents($url, false, $context);
$data = json_decode($result);
var_dump($data);
}
}
However when I'm using my class I get an error.
Warning: file_get_contents(http://crm-gateway.premier.com.au/GatewayService.svc/getbyquery) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\crm\includes\classes\RequestController.php on line 32
Can you please point out what I'm doing wrong?
Thanks,

How to get JSON in response

When I debug a site via Chrome browser I get JSON response. But when I try to do this via PHP I get an error message.
failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found
Thanks for any help.
For example:
Things to do in Chrome:
Go to page: http://gruper.pl/warszawa and on the bottom you will see a button "Wiecej ofert". After click you will see in a debug:
http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1
and response:
[{"ID_PAGE":"59199","ID_CITY":"3952","main_city":"3952","date_start":"2014-02-23 18:00:00","date_end":"2014-03-01 23:59:00","price".....
Is there any possibility to get the same in PHP?
My code is:
<?php
$url = 'http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1';
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"Accept:application/json\r\n" .
"Accept-Encoding:gzip,deflate,sdch\r\n" .
"X-Requested-With:XMLHttpRequest\r\n",
'method' => 'GET'
),
);
$context = stream_context_create($options);
$result = (file_get_contents($url, false, $context));
?>
<html>
<head>
<meta charset="UTF-8">
</head>
</html>
It looks like that URL will return a 404 HTTP status code unless these headers are set:
X-Requested-With: XMLHttpRequest
Referer: http://gruper.pl/warszawa
So this will work:
<?php
$url = 'http://gruper.pl/DataProvider.php?cityId=51&categoryId=0&mainNaviId=1&showBTile=true&page=1';
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "X-Requested-With: XMLHttpRequest\r\n" .
"Referer: http://gruper.pl/warszawa"
)
);
$context = stream_context_create($options);
$result = (file_get_contents($url, false, $context));
echo $result;
?>

passing headers into file_get_contents() for a json request

I need to pass these headers into the $context variable, i tried using putting the values into an array and then passing it into stream_context_create() function but i get http warnings from the file_getcontents function
$prod_id = 4322;
$tnxRef = "RT45635276GHF76783AC";
$mackey = "ADECNH576748GH638NHJ7393MKDSFE73903673";
$agent = $_SERVER['HTTP_USER_AGENT'];
$hash = hash('SHA512', $prod_id.$txnRef.$mackey);
$headers = array(
'http'=>(
'method'=>'GET',
'header'=>'Content: type=application/json \r\n'.
'$agent \r\n'.
'$hash'
)
)
stream_context_create($headers)
$url_returns = file_get_contents("https://test_server.com/test_paydirect/api/v1/gettransaction.json?productid=$prod_id&transactionreference=$txnRef&amount=$amount", false, $context);
$json = json_decode($url_returns, true);
Error:
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request`
Thats the error i get, can somebody please help with a definitive example.
You have several errors in your code.
The server returns 400 Bad Request, because your code would result in this incorrect HTTP request:
GET /test_paydirect/api/v1/gettransaction.json?productid=4322&transactionreference=RT45635276GHF76783AC&amount= HTTP/1.1
Host: test_server.com
Content: type=application/json
$agent
$hash
The errors are:
Variable expressions are not evaluated within single quotes
$amount is not set in your code example
The header is Content-Type: and not Content: type=
All headers (agent, hash) must have their corresponding name
Here is an example that should work:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'agent' => $agent,
'header' => "Content-Type: application/json\r\n"
. "X-Api-Signature: $hash"
)
)
);
Please note: X-Api-Signature is just an example - it depends on the API you are using how the API key header is named and how the hash is calculated. You should find this information in the Docs of your API!

Categories