cURL -d switch: How to use it in a guzzle request - php

I'm learning to use an API. They provide an example of the following authentication code:
curl -X POST --header "Content-Type: application/json" --header "Accept: application/json" -d " {\"Username\": \"the_username\",
\"Password\": \"the_password\"}
" "https://someurl.someapi.com:443/api/Login/Authenticate"
However I need to reproduce this with a Guzzle request. Here is what I've been trying
$headers = [
"Content-Type" => "application/json",
"Accept" => 'application/json -d " {\"Username\": \"the_username\", \"Password\": \"the_password\" }" ',
];
// $headers = [
// "Content-Type" => "application/json"
// ];
$extra_data = ["proxy" => $proxy,
"headers" => $headers ];
// Defining the Guzzle Client to communicate with Legacy.com
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://someurl.someapi.com:443/api/Login/Authenticate',
// You can set any number of default request options.
'timeout' => 10.0,
]);
try {
$response = $client->request('POST', '', $extra_data);
}
However no matter what I try (this was the latest of my failed attempts), I can't get anything other than a code 400 error.

So I finally figured how to do this:
This code worked!
$str = json_decode('{ "Username": "' . $username . '", "Password": "' . $password . '"}',true);
var_dump($str);
if ($str == NULL) return;
$url_authenticate = "Login/Authenticate";
$extra_data = ["proxy" => $proxy,
"json" => $str ];
// Defining the Guzzle Client to communicate with Legacy.com
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://someurl.someapi.com:443/api/',
// You can set any number of default request options.
'timeout' => 10.0,
]);
try {
$response = $client->request('POST', $url_authenticate, $extra_data);
}
catch (Exception $e) {
echo 'Exception: ' . $e->getResponse()->getStatusCode() . "\n";
exit;
}
$body = $response->getBody();
echo $body;
The key was use the json field int the extra data and transform the json to php array using json_decode. I hope this helps someone else

Related

Why newly minted api tokens for quickbooks fails in PHP but works in curl

When I refresh my api tokens for quickbooks with php sdk, they don't work with the php sdk. They only work with curl through command line. Why won't it work for php sdk? I will demonstrate this problem below:
The following script works PERFECTLY. It prints access token twice and the customer list:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2LoginHelper;
session_start();
function makeAPICall()
{
// Create SDK instance
$config = include('config.php');
$dataService = DataService::Configure(array(
'auth_mode' => 'oauth2',
'ClientID' => $config['client_id'],
'ClientSecret' => $config['client_secret'],
'RedirectURI' => $config['oauth_redirect_uri'],
'scope' => $config['oauth_scope'],
'baseUrl' => "development"
));
/*
* Retrieve the accessToken value from session variable
*/
$accessToken = $_SESSION['sessionAccessToken'];
echo "OLD ACCESS TOKEN:\n"; print_r($accessToken);
$oauth2LoginHelper = new OAuth2LoginHelper($config['client_id'], $config['client_secret']);
//$accessToken = $oauth2LoginHelper->refreshAccessTokenWithRefreshToken($accessToken->getRefreshToken());
/*
* Update the OAuth2Token of the dataService object
*/
$dataService->updateOAuth2Token($accessToken);
echo "NEW ACCESS TOKEN:\n"; print_r($accessToken);
$i = 0;
while (1) {
$allCustomers = $dataService->FindAll('Customer', $i, 500);
$error = $dataService->getLastError();
if ($error) {
echo "The Status code is: " . $error->getHttpStatusCode() . "\n";
echo "The Helper message is: " . $error->getOAuthHelperError() . "\n";
echo "The Response message is: " . $error->getResponseBody() . "\n";
exit();
}
if (!$allCustomers || (0==count($allCustomers))) {
break;
}
foreach ($allCustomers as $oneCustomer) {
echo "Customer[".($i++)."]: {$oneCustomer->DisplayName}<br/>";
echo "\t * Id: [{$oneCustomer->Id}]\n";
echo "\t * Active: [{$oneCustomer->Active}]\n";
echo "\n";
}
}
}
$result = makeAPICall();
If I enable the line $accessToken = $oauth2LoginHelper->refreshAccessTokenWithRefreshToken($accessToken->getRefreshToken());, I get the following output:
OLD ACCESS TOKEN:
QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken Object
(
[accessTokenKey:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..KPBgO13eC2F6tGTYO-eBjg.n1B1jaePPz9krqEaRuy3k5QO70CmMneddPKHq_U-_Lf4kHiOu5zhhhTIoSvmjoX7cB8HPqKZCkGo_oBTwrTHgvFVIRGxsk4iJOp8eMuM34s6FNux6mzeDGB89Q-yKzDuJbMSYInm694Tdyun6YgOwOlsktRPqktOWVXUqbt6wmGa0YARV8lAT8CX1YnlgzJsS2uz0qfgFufnQd3IPOtzVmgR7X40eu64qQmIseHRvETw5myVLnkKHNPrjCAzr97-TtCZpxx9MIKqaSzDoDlnko4gOHUQB_eWrbTC9j3eeI2vX8xNFrHQh34SgSDWJBBvWdDuEgxCzJwdkvXd_c2yhW4jRJrgGuE7456EJjz7Qm-j2emWKLAS5SRJcEHcYYIZvKa1gO1SvsF0YMNz3aanyfP-ci-J_ipuVv4-lu_-NBjfopzieSLkbsJob6voVLAmEdXDAg2hjXe9VjAoI_fcPnMS_Nxt3bvXd2DLbqKDi5x0zatRQVVzSV9npOUz2Rwd2k7XtsdzkwzvVg9Nw3M-XZp7USgXzNqqIQCqzZqqWSomUsxtB7ZLlAXBR32pj_8Thnj2ail_qW_KpBlqqKtij-T0dbprx-I0hWGDOnpUFhCmip-oKLocBiAugBMWAaY6IHZ2U9tmZhWDC5XNbhqy_NLIkjh5YPBrAv3EvizGa1l_hfS3oc86EGpvFoBf8bvWpqkJiZt1vYNkvDV6pOk1ZgOmpPqhiRw-HEOAmBzONC3VI57u0dwVkM1m95HoSI4T49BFQSg5B1Rvg6BY3D_IKIT7Ve2dyTf0ApZXhPnZXqq3sDuy6b1113v-Q5k9xfa8TRNFZmkA5XN4tjy0bpO4sue5wGO-BG0aMBntM-1VEKvp0t2m3u2-RWJ6X2x3uvwn.YTlB02ihKoPJFoxHyuidhQ
[tokenType:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => bearer
[refresh_token:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => AB11619101552M4mvRdPUzPdddQQQDrruD2sf4Wc1nJ69GJsTs
[accessTokenExpiresAt:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 1610378752
[refreshTokenExpiresAt:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 1619101552
[accessTokenValidationPeriod:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 3600
[refreshTokenValidationPeriod:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 8726400
[clientID:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => AB5xEvDqPW14gGkIz5cEBWsaUQkK9gP7gg8zDrsWtay4JcqISS
[clientSecret:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => FJJG6S6Lr9NxTJOynnH448FZ9A3sVNEIT2exlezB
[realmID:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 4620816365156528260
[baseURL:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] =>
)
NEW ACCESS TOKEN:
QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken Object
(
[accessTokenKey:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..t-Dz4BeWjc8YKRyi2gESsw.YiG8g5LYBkI7s39gc_PfDWMoeNJfPPMh6ExTNONcWhDV1_H6cglhmttm4F1Hd-0xxGMtISYSxwH2ywCxn7Bz9twf-1R-QMv4k70nYrn8fesNi0OY9FsHl2ZHX7xJo76eUkCq1PQFV9iiZ4khL0VGXm-C8Cyqogzh23CdnjIJqG2s3ykhtUWjCHSy2PRpU1-_FZzBlFFUqxigeuLU8u1fLj7NAVuVzxx0sSEBNNl76fQ-iAzwjmuGBiM1IxgCSbRWJqMXoZPcuPuKD-lD8-EZMB4pNfJCjYeA2qRZ9COycaK_iJh9vuIfTTq49GhdwbIiBggvc0BbyccaGtQNK4UfLlb7SRogfG-AxRhNq1g54fOo9PkfeZ5Mn2VAWxgKzPLRbIupXIcwOpiWJVMz3zFvjBd64qj8OzITPhYhz0hJ5rATdBe3U20Z4DA8Klqy3A6DshCaiEwBFwd8QKmmorAFLF8HBWuD4kHVn5_NuuMsviqhN0JLkQ0JwZ01WsUxMEvS9Lj6O_OqFzpjWZrqNO8hW6k7GAX5tcnw2TaISL9l6eEXH_C3MQwg9fcKItehiPtQReM4rylgXfcfIQWVn1BiReOV2ctlcZbzhmi5WXsDU_0fxQdhr49DLZttiPDYA4iiCRY6BogbpeOg7_ekZpzpTpYYZzVWwapxreT6ZawrPYkq_KCxbMqJ8vL8uToDpfdHFPF92ITmIAQkuFGsji2ay4GnnAjHqmXey5tboWc0ahmHyZJh4Ujr_Mr1jnycHyXjK-_zLuuT036P2zCmZdgHR3sfv4G3wKeiqw8brKLj2J3ft441AS7FsuwnIXO0xZfefFdBX38yElqyDdCnSUm0KvIxQKW6-Veu4qr8aLuNG-RtJWO47BgRbCZguxoyNbXo.6x5sd3kIBdvUBsmfXkKSgg
[tokenType:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => bearer
[refresh_token:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => AB11619101552M4mvRdPUzPdddQQQDrruD2sf4Wc1nJ69GJsTs
[accessTokenExpiresAt:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 1610378756
[refreshTokenExpiresAt:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 1619101552
[accessTokenValidationPeriod:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 3600
[refreshTokenValidationPeriod:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 8726396
[clientID:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => AB5xEvDqPW14gGkIz5cEBWsaUQkK9gP7gg8zDrsWtay4JcqISS
[clientSecret:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => FJJG6S6Lr9NxTJOynnH448FZ9A3sVNEIT2exlezB
[realmID:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] =>
[baseURL:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] =>
)
The Status code is: 400
The Helper message is: Invalid auth/bad request (got a 400, expected HTTP/1.1 20X or a redirect)
The Response message is: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2021-01-11T06:25:56.985-08:00"><Fault type="ValidationFault"><Error code="500"><Message>Unsupported Operation</Message><Detail>Operation Could not find resource for relative : /v3/company/query of full path: https://c50.sandbox.qbo.intuit.com/qbo50/v3/company/query?minorversion=57 is not supported.</Detail></Error></Fault></IntuitResponse>
As shown above, querying for customers with new token gives 400 error. Both tokens work if I use curl:
Success with old token:
curl -X GET 'https://sandbox-quickbooks.api.intuit.com/v3/company/4620816365156528260/query?query=SELECT%20*%20FROM%20Customer' \
-H 'accept: application/json' \
-H 'authorization:Bearer eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..KPBgO13eC2F6tGTYO-eBjg.n1B1jaePPz9krqEaRuy3k5QO70CmMneddPKHq_U-_Lf4kHiOu5zhhhTIoSvmjoX7cB8HPqKZCkGo_oBTwrTHgvFVIRGxsk4iJOp8eMuM34s6FNux6mzeDGB89Q-yKzDuJbMSYInm694Tdyun6YgOwOlsktRPqktOWVXUqbt6wmGa0YARV8lAT8CX1YnlgzJsS2uz0qfgFufnQd3IPOtzVmgR7X40eu64qQmIseHRvETw5myVLnkKHNPrjCAzr97-TtCZpxx9MIKqaSzDoDlnko4gOHUQB_eWrbTC9j3eeI2vX8xNFrHQh34SgSDWJBBvWdDuEgxCzJwdkvXd_c2yhW4jRJrgGuE7456EJjz7Qm-j2emWKLAS5SRJcEHcYYIZvKa1gO1SvsF0YMNz3aanyfP-ci-J_ipuVv4-lu_-NBjfopzieSLkbsJob6voVLAmEdXDAg2hjXe9VjAoI_fcPnMS_Nxt3bvXd2DLbqKDi5x0zatRQVVzSV9npOUz2Rwd2k7XtsdzkwzvVg9Nw3M-XZp7USgXzNqqIQCqzZqqWSomUsxtB7ZLlAXBR32pj_8Thnj2ail_qW_KpBlqqKtij-T0dbprx-I0hWGDOnpUFhCmip-oKLocBiAugBMWAaY6IHZ2U9tmZhWDC5XNbhqy_NLIkjh5YPBrAv3EvizGa1l_hfS3oc86EGpvFoBf8bvWpqkJiZt1vYNkvDV6pOk1ZgOmpPqhiRw-HEOAmBzONC3VI57u0dwVkM1m95HoSI4T49BFQSg5B1Rvg6BY3D_IKIT7Ve2dyTf0ApZXhPnZXqq3sDuy6b1113v-Q5k9xfa8TRNFZmkA5XN4tjy0bpO4sue5wGO-BG0aMBntM-1VEKvp0t2m3u2-RWJ6X2x3uvwn.YTlB02ihKoPJFoxHyuidhQ' \
-H 'content-type: application/json'
Success with new token:
curl -X GET 'https://sandbox-quickbooks.api.intuit.com/v3/company/4620816365156528260/query?query=SELECT%20*%20FROM%20Customer' \
-H 'accept: application/json' \
-H 'authorization:Bearer eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..t-Dz4BeWjc8YKRyi2gESsw.YiG8g5LYBkI7s39gc_PfDWMoeNJfPPMh6ExTNONcWhDV1_H6cglhmttm4F1Hd-0xxGMtISYSxwH2ywCxn7Bz9twf-1R-QMv4k70nYrn8fesNi0OY9FsHl2ZHX7xJo76eUkCq1PQFV9iiZ4khL0VGXm-C8Cyqogzh23CdnjIJqG2s3ykhtUWjCHSy2PRpU1-_FZzBlFFUqxigeuLU8u1fLj7NAVuVzxx0sSEBNNl76fQ-iAzwjmuGBiM1IxgCSbRWJqMXoZPcuPuKD-lD8-EZMB4pNfJCjYeA2qRZ9COycaK_iJh9vuIfTTq49GhdwbIiBggvc0BbyccaGtQNK4UfLlb7SRogfG-AxRhNq1g54fOo9PkfeZ5Mn2VAWxgKzPLRbIupXIcwOpiWJVMz3zFvjBd64qj8OzITPhYhz0hJ5rATdBe3U20Z4DA8Klqy3A6DshCaiEwBFwd8QKmmorAFLF8HBWuD4kHVn5_NuuMsviqhN0JLkQ0JwZ01WsUxMEvS9Lj6O_OqFzpjWZrqNO8hW6k7GAX5tcnw2TaISL9l6eEXH_C3MQwg9fcKItehiPtQReM4rylgXfcfIQWVn1BiReOV2ctlcZbzhmi5WXsDU_0fxQdhr49DLZttiPDYA4iiCRY6BogbpeOg7_ekZpzpTpYYZzVWwapxreT6ZawrPYkq_KCxbMqJ8vL8uToDpfdHFPF92ITmIAQkuFGsji2ay4GnnAjHqmXey5tboWc0ahmHyZJh4Ujr_Mr1jnycHyXjK-_zLuuT036P2zCmZdgHR3sfv4G3wKeiqw8brKLj2J3ft441AS7FsuwnIXO0xZfefFdBX38yElqyDdCnSUm0KvIxQKW6-Veu4qr8aLuNG-RtJWO47BgRbCZguxoyNbXo.6x5sd3kIBdvUBsmfXkKSgg' \
-H 'content-type: application/json'
So my question is how do I query for customers via php sdk with the new access token?
EDIT, by the time you read this message, the tokens may have expired for you. But I want to emphasize that both curl statements I posted above will work if you run them at the same time.
If necessary, I can generate new tokens again for everyone to try out.
This was happening to me as well after refreshing the access token using:
$token = $loginHelper->refreshAccessTokenWithRefreshToken($refresh_token);
After that I had to set the realmId in the token as such:
$token->setRealmID($myRealmId);
and it worked.
Even weirder though, I was doing that in a Trait function and returning my updated access token (with the realmId already set, supposedly), but when I was trying to make a call to query using the SDK:
$dataService->query("select * from class");
it was still giving me that error. So, after returning the access token and before trying to use it for query, I had to set the realmId again.

GuzzleHttp\Client 400 bad request on Laravel 5.5

I am sending a POST request to an API, Curl returns 200 and the correct response.
When Implementing with GuzzleHttp\Client, I get a 400 Bad request, what is wrong with my formatting.
here is my code using Laravel Returns 400 Bad Request:
$client = new Client();
$URI = 'http://api.example.com';
$params['headers'] = ['Content-Type' => 'application/json',
'apikey' => config('app._api_key'),
'debug' => true
];
$params['form_params'] = [
'sender' => 'Test_sender',
'recipient' => config('app.test_recipient'),
'message_body' => 'Test body'
];
return $response = $client->post($URI, $params);
Curl (Returns 200):
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'apikey: 212121212’ -d '{ "message_body": "test","sender": "2018","recipient": “4453424141” }' 'http://api.example.com'
Try the below code:
$client = new \GuzzleHttp\Client(['headers' => ['Content-Type' => 'application/json',
'apikey'=> config('app._api_key'),
'debug' => true
]
]);
$URI = 'http://api.example.com';
$body['sender']='Test_sender';
$body['recipient']=config('app.test_recipient');
$body['message_body']='Test body';
$body=json_encode($body);
$URI_Response = $client->request('POST',$URI,['body'=>$body]);
$URI_Response =json_decode($URI_Response->getBody(), true);
return $URI_Response;
Note: I would suggest you to handle error please refer GuzzleDocumentation
That is proper error handling:
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
try {
$response = $client->get(YOUR_URL, [
'connect_timeout' => 10
]);
// Here the code for successful request
} catch (RequestException $e) {
// Catch all 4XX errors
// To catch exactly error 400 use
if ($e->getResponse()->getStatusCode() == '400') {
echo "Got response 400";
}
// You can check for whatever error status code you need
} catch (\Exception $e) {
// There was another exception.
}
Implementation: http://guzzle.readthedocs.org/en/latest/quickstart.html
You can handle errors like this
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use Exception;
try{
$client = new Client();
$response = $client->request('POST', $url,[
'headers' => $header,
'form_params' => $form-params
]);
$body = $response->getBody();
$status = 'true';
$message = 'Data found!';
$data = json_decode($body);
}catch(ClientException $ce){
$status = 'false';
$message = $ce->getMessage();
$data = [];
}catch(RequestException $re){
$status = 'false';
$message = $re->getMessage();
$data = [];
}catch(Exception $e){
$this->status = 'false';
$this->message = $e->getMessage();
$data = [];
}
return ['status'=>$status,'message'=>$message,'data'=>$data];

Multiple post xml data in guzzle and multiple async request

How can I create an asynchronous request to multiple URI with different post data for each?
I am able to get the data for each of the URI, but I want to make it asynchronous.
Also, how do I timeout if the request takes too long?
My code:
//url
$ur1 = 'www.exaample1.com';
$ur2 = 'www.Test.com';
//xml
$ur1_xml = ''; // xml code
$ur2_xml = ''; // xml code
//headers
$ur1_header = array("POST HTTP/1.1",
"Content-type: application/xml; charset=\"utf-8\"",
"Content-length: " . strlen($ur1_xml));
$ur2_header = array("POST HTTP/1.1",
"Content-type: application/xml; charset=\"utf-8\"",
"Content-length: " . strlen($ur2_xml));
$client = new Client();
// make request
$request = new Request('POST', $ur1_url, $ur1_headers,$ur1_xml);
$promise = $client->sendAsync($request)->then(function ($response) {
echo '<pre>';
print_r(simplexml_load_string($response->getBody()));
echo '</pre>';
});
die();
For application/x-www-form-urlencoded send Async requests you can get benefit from Guzzle promises. Headers and POST fields should go into an array as documents state.
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
.
.
.
$client = new Client();
$promises = [
$client->postAsync($url1, ['headers' => $headers1, 'form_params' => $postData1]),
$client->postAsync($url2, ['headers' => $headers2, 'form_params' => $postData2]),
$client->postAsync($url3, ['headers' => $headers3, 'form_params' => $postData3])
];
$results = Promise\unwrap($promises);
$results = Promise\settle($promises)->wait();
// response headers of first request
print_r($results[0]['value']->getHeaders());
// retrieved contents of second request
echo $results[1]['value']->getBody()->getContents();

GuzzleHTTP POST equivalent to curl -X POST -H --data "name=myname&email=test#test.com" https://api.test.com/accounts

I have the following CURL Request to an API:
curl -X POST -H "X-Api-Key:somekey" --data "name=myname&email=test#test.com" https://api.test.com/accounts
What is the Equivalent script to use in GuzzleHTTP Psr7.
I tried the following but didn't work, it didn't receive the $query data array.
$query = [
'name'=>'MyName',
'email'=>'Email#think-ds.com',
];
$client = new Client([
'base_uri' => 'https://api.test.com/v1/',
'verify' =>'cert.pem',
]);
$headers=['form_params'=>$query];
try{
$request = new Request('POST', 'accounts', $headers);
$response = $client->send($request);
} catch (\GuzzleHttp\Exception\ClientException $e) {
die($e->getResponse()->getBody()->getContents()); exit;
}
var_dump($response->getBody());

Sending push notification toast to windows phone using Parse api through php web services

I need to send push messages from my web service to the windows phone. I am able to achieve this from console, however i need to do this using a php script
Code i have tried:
$url = 'https://api.parse.com/1/push';
$appId = 'xxx';
$restKey = 'xxx';
$push_payload = json_encode(array(
"where" => '"deviceType"=>"winrt"',
"data" => array(
"alert" => "This is the alert text."
)
));
$rest = curl_init();
curl_setopt($rest,CURLOPT_URL,$url);
curl_setopt($rest,CURLOPT_PORT,443);
curl_setopt($rest,CURLOPT_POST,1);
curl_setopt($rest,CURLOPT_POSTFIELDS,$push_payload);
curl_setopt($rest,CURLOPT_HTTPHEADER,
array("X-Parse-Application-Id: " . $appId,
"X-Parse-REST-API-Key: " . $restKey,
"Content-Type: application/json"));
$response = curl_exec($rest);
echo $response;
var_dump($response);
}
But on the dumping the response i get a boolean value:false and no notification appears on the phone.
Try this:
$push_payload = json_encode(array(
"where" => array("deviceType" => "winrt"),
"data" => array("alert" => "This is the alert text.")
));

Categories