I'm trying to make a json call with a variable, but keep getting an error since the call isn't registering quotes.
The following syntax makes the notification push send correctly:
'include_player_ids' => array('00000000-6fee-11e4-8ec9-000000000000')
Where as this method causes it to fail:
$playerID = '00000000-6fee-11e4-8ec9-000000000000';
...
'include_player_ids' => array($playerID)
The reason being the api requires the quotes around the array item, but I'm not too great at php and can't figure out how to add them around it since this method isn't working for me:
'include_player_ids' => array(' . $playerID . '),
Good (working) output:
"include_player_ids":["00000000-6fee-11e4-8ec9-000000000000"]
Bad (non-working) output:
"include_player_ids":[00000000-6fee-11e4-8ec9-000000000000]
Sending the POST request as json (with header set to "Content-Type" => "application/json") should work:
$fields = (object) [
'app_id' => $this->appId,
'include_player_ids' => $playerIds,
'template_id' => '374e7074-f07d-4743-ad90-5598967e4494', // `daily generic`
];
json_encode($fields);
Related
I am trying to connect to the Listmonk API through wp_remote_post() on WordPress. I created a custom plugin for this.
Some parts work, but when I need to submit data that is an array or integer, I get errors. Also when I try to use wp_json_encode(), as recommended online, the API gives me a 400 error.
I hope someone can help!
I tried a lot of things. My POST code is:
$response = wp_remote_post($listmonk_url, array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode($listmonk_username . ':' . $listmonk_password),
'Content-Type: application/json',
),
'body' => $body,
));
And my body content is:
$body = array(
'name' => $name,
'email' => $email,
'status'=> 'enabled',
'lists' => 2,
'preconfirm_subscriptions' => true,
) ;
Whenever I try to use wp_json_encode() on $body, the API gives me:
[http_response] => WP_HTTP_Requests_Response Object ( [response:protected] => Requests_Response Object ( [body] => {"message":"Invalid email."} [raw] => HTTP/1.1 400 Bad Request Server
The encoded JSON was:
{"name":"john","email":"jan#jan.com","status":"enabled"}
And when I don't use json encoding, my 'lists' never passes through correctly, as you can see below, where the returned JSON shows lists is empty:
"lists":[]}
Is there something I am not seeing?
Before I begin with my question, I will mention that I am re-learning PHP after a long time away from the language. Please be gentle. Also, I know that I could use a library like curl to do some of these things, but I would like to understand how PHP works natively.
I am trying to submit an http GET request to a Microsoft API (Identity Platform). The following is my code:
<?php
$data = array (
'client_id' => '6731de76-14a6-49ae-97bc-6eba6914391e',
'state' => '12345',
'redirect_uri' => urlencode('http://localhost/myapp/permissions')
);
$streamOptions = array('http' => array(
'method' => 'GET',
'content' => $data
));
$streamContext = stream_context_create($streamOptions);
$streamURL = 'https://login.microsoftonline.com/common/adminconsent';
$streamResult = file_get_contents($streamURL, false, $streamContext);
echo $streamResult;
?>
When I try and execute the above code, I get this:
Error snip
Conversely, with the following code, the http request works fine:
<?php
$streamURL = 'https://login.microsoftonline.com/common/adminconsent?client_id=6731de76-14a6-49ae-97bc-6eba6914391e&state=12345&redirect_uri=http://localhost/myapp/permissions';
$streamResult = file_get_contents($streamURL);
echo $streamResult;
?>
Can anyone provide insight as to why the first example fails while the second succeeds? My thought is that there must be some kind of syntactical error. Thanks in advance.
The content parameter is for the request body, for POST and PUT requests. But GET parameters don't go in the body, they go right on the URL. So your first example is simply making a GET request to the base URL with no parameters at all. Note also that the method parameter already defaults to GET, so you can just skip the whole streams bit.
You can build your URL like:
$urlBase = 'https://login.microsoftonline.com/common/adminconsent';
$data = [
'client_id' => '...',
'state' => '12345',
'redirect_uri' => 'http://localhost/myapp/permissions',
];
$url = $urlBase . '?' . http_build_query($data);
And then just:
$content = file_get_contents($url);
Or just cram it all into one statement:
$content = file_get_contents(
'https://login.microsoftonline.com/common/adminconsent?' .
http_build_query([
'client_id' => '...',
'state' => '12345',
'redirect_uri' => 'http://localhost/myapp/permissions',
])
);
Or use $url to feed curl_init() or Guzzle or similar.
I use Guzzle6 in the PSR7 flavor because it integrates nicely with Hawk authentication. Now, I face problems adding a body to the request.
private function makeApiRequest(Instructor $instructor): ResponseInterface
{
$startDate = (new CarbonImmutable('00:00:00'))->toIso8601ZuluString();
$endDate = (new CarbonImmutable('00:00:00'))->addMonths(6)->toIso8601ZuluString();
$instructorEmail = $instructor->getEmail();
$body = [
'skip' => 0,
'limit' => 0,
'filter' => [
'assignedTo:user._id' => ['email' => $instructorEmail],
'start' => ['$gte' => $startDate],
'end' => ['$lte' => $endDate],
],
'relations' => ['reasonId']
];
$request = $this->messageFactory->createRequest(
'POST',
'https://app.absence.io/api/v2/absences',
[
'content_type' => 'application/json'
],
json_encode($body)
);
$authentication = new HawkAuthentication();
$request = $authentication->authenticate($request);
return $this->client->sendRequest($request);
}
When I var_dump the $request variable, I see no body inside the request. This is backed by the fact that the API responds as if no body was sent. I cross-checked this in Postman. As you can see, the body specifies filters and pagination, so it is easy to see that the results I get are actually not filtered.
The same request in Postman (with body) works flawlessly.
As the parameter be can of type StreamInterface I created a stream instead and passed the body to it. Didn't work either.
Simple JSON requests can be created without using json_encode()... see the documentation.
use GuzzleHttp\Client;
$client = new Client([
'base_uri' => 'https://app.absence.io/api/v2',
'timeout' => 2.0
]);
$response = $client->request('POST', '/absences', ['json' => $body]);
Found the problem, actually my POST body is NOT empty. It just turns out that dumping the Request will not hint anything about the actual body being enclosed in the message.
I can recommend anyone having similar problems to use http://httpbin.org/#/HTTP_Methods/post_post to debug the POST body.
Finally, the problem was that my content_type header spelling was wrong as the server expects a header Content-Type. Because of this, the JSON data was sent as form data.
$response = $facebook->api(
'me/objects/namespace:result',
'POST',
array(
'app_id' => app_id,
'type' => "namespace:result",
'url' => "http://samples.ogp.me/370740823026684",
'title' => "Sample Result",
'image' => "https://fbstatic-a.akamaihd.net/images/devsite/attachment_blank.png",
'description' => ""
)
);
I get the following error.
The parameter object is required
I don't know where to add the parameter object.
I have been facing the same issue for the past couple of days, in the end I stopped trying to use the Facebook PHP SDK to send the request and resorted to using just sending a HTTP Request.
I am creating an object rather than updating one, but the implementation shouldn't differ much from your needs. I was getting the same error (The parameter object is required) and the below implementation resolved that issue.
I used the vinelab HTTP client composer package and built a request like this:
$request = [
'url' => 'https://graph.facebook.com/me/objects/namespace:object',
'params' => [
'access_token' => $fbAccessToken,
'method' => 'POST',
'object' => json_encode([
'fb:app_id' => 1234567890,
'og:url' => 'http://samples.ogp.me/1234567890',
'og:title' => 'Sample Object',
'og:image' => 'https://fbstatic-a.akamaihd.net/images/devsite/attachment_blank.png',
'og:description' => 'Sample Object'
])
]
];
// I'm using Laravel so this bit might look different for you (check the vine lab docs if you use that specific HTTP client)
$response = HttpClient::post($request);
// raw content
$response->content();
// json
$response->json();
As I said, I used the vinelab HTTP package in my implementation, you should be able to use any similar package or directly use curl in PHP instead.
The following soap request
$response = $this->client->__soapCall('Match', array('word' => 'test', 'strategy' => 'exact'));
yields the error
Uncaught SoapFault exception: [soap:Client] Parameter not specified (null)
Parameter name: word
How can this be? I specified the word parameter in the request, didnt I? Why doesn's the server recognize it?
The service I want to use is an online dictionary webservive
Generally you need to wrap the arguments in a double array:
$response = $this->client->__soapCall('Match', array(array('word' => 'test', 'strategy' => 'exact')));
It reads a bit nicer if you
$aParams = array('word' => 'test', 'strategy' => 'exact');
$response = $this->client->__soapCall('Match', array($aParams));
Or you can simply call the Match function directly
$aParams = array('word' => 'test', 'strategy' => 'exact');
$response = $this->client->Match($aParams);
Or, as a final resort, use the HTTP GET option: http://services.aonaware.com/DictService/DictService.asmx?op=Match
Should get you on the road again.