I'm trying create a PHP class to send Push Notification. When I try send push doesn't works an throws an exception of syntax error and I can't find this error. I'm using PHP 5.3.28.
How could I solve it ?
Pusher
<?php
class Pusher{
const GOOGLE_GCM_URL = 'https://android.googleapis.com/gcm/send';
private $apiKey;
private $proxy;
private $output;
public function __construct($apiKey, $proxy = null)
{
$this->apiKey = $apiKey;
$this->proxy = $proxy;
}
/**
* #param string|array $regIds
* #param string $data
* #throws \Exception
*/
public function notify($regIds, $data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::GOOGLE_GCM_URL);
if (!is_null($this->proxy)) {
curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->getPostFields($regIds, $data));
$result = curl_exec($ch);
if ($result === false) {
throw new \Exception(curl_error($ch));
}
curl_close($ch);
$this->output = $result;
}
/**
* #return array
*/
public function getOutputAsArray()
{
return json_decode($this->output, true);
}
/**
* #return object
*/
public function getOutputAsObject()
{
return json_decode($this->output);
}
private function getHeaders(){
return [
'Authorization: key=' . $this->apiKey,
'Content-Type: application/json'
];
}
private function getPostFields($regIds, $data){
$fields = [
'registration_ids' => is_string($regIds) ? [$regIds] : $regIds,
'data' => is_string($data) ? ['message' => $data] : $data,
];
return json_encode($fields, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
}
}
Exception
Fatal Error
Error: syntax error, unexpected '['
File: /app/Plugin/Push/Pusher.php
Line: 60
At line 60 have
private function getHeaders(){
return [
'Authorization: key=' . $this->apiKey,
'Content-Type: application/json'
];
}
Related
This question already has answers here:
Constructor returning value?
(6 answers)
Closed 10 months ago.
In my laravel app I use curl to send notifications via FCM (Firebase Cloud Messaging) rest API using curl and php, when I execute curl I save result to result variable along with http code and return it, however what I receive in $notification variable is the parametters passed to NewMatchMotif instead of curl result:
$notification = new NewMatchNotif($user, $data, 'es');
Something like this:
{user: {…}, data: {…}, locale: "es"}
My NewMatch Notification:
<?php
namespace App\Notifications;
use App\Helpers\CloudMessaging;
use Lang;
use Log;
class NewMatchNotif
{
public $user;
public $data;
public $locale;
public function __construct($user, $data, $locale)
{
$this->user = $user;
$this->data = $data;
$this->locale = $locale;
$this->load();
}
public function load()
{
$cloudMessaging = new CloudMessaging();
$result = $cloudMessaging->send($this->user, 'title', 'body', $this->data, 'NewMatchNotif');
return $result;
}
}
My send method
public function send($user,$title,$body, $data = false , $type, $image='')
{
$fields = '...';
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = json_encode($fields);
$headers =
[
'Authorization: key='. config('services.firebase.api_key'),
'Content-Type: application/json',
];
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY , true);
$result = curl_exec ( $ch );
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ( $ch );
$output =
[
'httpCode' => $httpcode,
'result' => $result
];
return $output;
}
What is going on, this part is pretty straight fordward yet I'm not getting the desired results:
$result = curl_exec ( $ch );
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ( $ch );
$output =
[
'httpCode' => $httpcode,
'result' => $result
];
return $output;
you need to get the result after instanciate the class, like:
<?php
namespace App\Notifications;
use App\Helpers\CloudMessaging;
use Lang;
use Log;
class NewMatchNotif
{
public $user;
public $data;
public $locale;
public $result;
public function __construct($user, $data, $locale)
{
$this->user = $user;
$this->data = $data;
$this->locale = $locale;
$this->load();
}
private function load()
{
$cloudMessaging = new CloudMessaging();
$this->result = $cloudMessaging->send($this->user, 'title', 'body', $this->data, 'NewMatchNotif');
}
}
And then:
$notification = (new NewMatchNotif($user, $data, 'es'))->result;
Here is my code, and I can't figure out why it's not working.
$soapUrl = "http://airarabia.isaaviations.com/webservices/services/AAResWebServices?wsdl";
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Header><wsse:Security soap:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><wsse:UsernameToken wsu:Id="UsernameToken-17855236" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><wsse:Username>xxx</wsse:Username><wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">xxx</wsse:Password></wsse:UsernameToken></wsse:Security></soap:Header><soap:Body xmlns:ns2="http://www.opentravel.org/OTA/2003/05"><ns2:OTA_AirAvailRQ EchoToken="11868765275150-1300257933" PrimaryLangID="en-us" SequenceNmbr="1" Target="LIVE" TimeStamp="2018-10-08T11:39:35" Version="20061.00"><ns2:POS><ns2:Source TerminalID="Farhath/Farhath"><ns2:RequestorID ID="WSBENZTRAVELS" Type="4" /><ns2:BookingChannel Type="12" /></ns2:Source></ns2:POS><ns2:OriginDestinationInformation><ns2:DepartureDateTime>2018-10-30T00:00:00</ns2:DepartureDateTime><ns2:OriginLocation LocationCode="CMB" /><ns2:DestinationLocation LocationCode="RUH" /></ns2:OriginDestinationInformation><ns2:OriginDestinationInformation><ns2:DepartureDateTime>2018-11-30T00:00:00</ns2:DepartureDateTime><ns2:OriginLocation LocationCode="RUH" /><ns2:DestinationLocation LocationCode="CMB" /></ns2:OriginDestinationInformation><ns2:TravelerInfoSummary><ns2:AirTravelerAvail><ns2:PassengerTypeQuantity Code="ADT" Quantity="1" /></ns2:AirTravelerAvail></ns2:TravelerInfoSummary></ns2:OTA_AirAvailRQ></soap:Body></soap:Envelope>';
$headers = array(
"Host: airarabia.isaaviations.com",
"Content-Type: application/soap+xml; charset=utf-8",
"Content-Length: ".strlen($xml_post_string)
);
$url = $soapUrl;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
$parser = simplexml_load_string($response);
print_r($parser);
I am able to connect to the API, but couldn't get a result.
Do you have any idea, any solution ?
I wrote a class that helps to simplify generating SOAP XML for a Laravel package. Here is the class:
<?php
namespace Mtownsend\CollectionXml\Soap;
use SoapClient;
/**
* Use the SoapFactory class to build a valid SOAP request
* but prevent it from making an actual request
* and capture the data it builds for use.
*/
class SoapFactory extends SoapClient
{
public $soapRequest;
public $soapLocation;
public $soapAction;
public $soapVersion;
public function __construct($wsdl, $options)
{
parent::__construct($wsdl, $options);
}
/**
* Build the SOAP xml string
* #param array $soapRootAndXml [$soapRoot => $xml]
* #return Mtownsend\CollectionXml\Soap\SoapFactory
*/
public function build(array $soapRootAndXml)
{
$this->ProcessXMLRequest($soapRootAndXml);
return $this;
}
/**
* Override the SoapClient __doRequest method.
*/
public function __doRequest($request, $location, $action, $version, $one_way = 0)
{
$this->soapRequest = $request;
$this->soapLocation = $location;
$this->soapAction = $action;
$this->soapVersion = $version;
return ''; // Return a string value or the SoapClient throws an exception
}
/**
* A proxy for the getSoapRequest method.
* #return string
*/
public function getSoapXml()
{
return $this->getSoapRequest();
}
/**
* Return the SOAP request XML.
* #return string
*/
public function getSoapRequest()
{
return $this->soapRequest;
}
/**
* Return the SOAP request location url.
* #return string
*/
public function getSoapLocation()
{
return $this->soapLocation;
}
/**
* Return the SOAP request action.
* #return string
*/
public function getSoapAction()
{
return $this->soapAction;
}
/**
* Return the SOAP request version number.
* #return string
*/
public function getSoapVersion()
{
return $this->soapVersion;
}
}
If you would like to use it, save the contents to SoapFactory.php and include it in your script.
Next, get your raw xml ready. Don't try to SOAPify it or anything. Store it in a variable $xml_post_string.
You may need to change your soap root if it doesn't work. I've connected to soap endpoints in the past that use 'xmlBody'.
$soapRoot = 'xmlBody';
$soapFactory = new SoapFactory($soapUrl, ['trace' => 1]));
$soapXml = $soapFactory->build([$soapRoot => $xml_post_string])->getSoapXml();
Now you can try a curl call.
$headers = array(
"Host: airarabia.isaaviations.com",
"Content-Type: application/soap+xml; charset=utf-8",
"Content-Length: ".strlen($soapXml)
);
$url = $soapUrl;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $soapXml);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$parser = simplexml_load_string($response);
print_r($parser);
There's no guarantee with SOAP, but try that and see if it gets you anywhere.
When I call route in Slim php from the browser it works perfectly, however when I call it via Ajax I recieve a 404 error. The function in question makes a Curl request. I suspect this may have something to do with the headers I'm sending with curl:
$data = $this->curl->call($url, $urlParams, $postParams, $method, $this->getDefaultHeaders());
protected function getDefaultHeaders() {
return array(
'Authorization' => 'Bearer ' . $this->access_token,
'Accept' => self::HTTP_HEADER_ACCEPT,
);
}
class Curl {
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_DELETE = 'DELETE';
const CURL_TIMEOUT_IN_SECS = 15;
public static $successFullHttpCodes = array(200, 201, 204);
public function call($url, $urlParams = array(), $postParams = null, $method = self::METHOD_GET, $headers = array()) {
$finalUrl = $url . $this->getUrlParameterString($urlParams);
$data = $this->makeCurlCall($finalUrl, $postParams, $method, $headers);
return $data;
}
/**
* Creates a curl call for the given url, automatically validates the return value for errors.
* If an error has been found a new Exception will be thrown.
*
* #param string $url
* #param array $postParams Parameters for Post and Put-Requests
* #param string $method HTTP-Method (GET, PUT, POST, DELETE)
* #param string $headers HTTP-Headers
* #throws Exception
*/
private function makeCurlCall($url, $postParams = array(), $method = self::METHOD_GET, $headers = array()) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_TIMEOUT, self::CURL_TIMEOUT_IN_SECS);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
if ($headers) {
$usableHeaders = array();
foreach ($headers as $name => $value) {
$usableHeaders[] = sprintf('%s: %s', $name, $value);
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $usableHeaders);
}
if ($postParams) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $postParams);
}
$data = curl_exec($curl);
$this->checkForError($curl, $data);
return $data;
}
/**
* Checks for any errors in the api response.
* If an error has been found a new Exception will be thrown.
*
* #param string $data the resulting data
* #throws Exception
*/
private function checkForError($curl, $data) {
$curlInfo = curl_getinfo($curl);
if (isset($curlInfo['http_code']) && !in_array($curlInfo['http_code'], self::$successFullHttpCodes)) {
throw new Exception($curlInfo['http_code'] ? $data : 'could not get a response from the service...'.$curl." data: ".$data, $curlInfo['http_code'] ? $curlInfo['http_code'] : 500);
}
}
/**
* Builds a valid http query
*
* #param array $urlParams
* #return string
*/
private function getUrlParameterString(array $urlParams) {
if (!$urlParams) {
return "";
}
return "?" . http_build_query($urlParams);
}
}
It turns out my error was with storing the api token in a session variable when there are two different sessions evoked.
I came across the project where I need to implement web services protected by NTLM authentication.
I gave it try via PHP SoapClient:
$client = new \SoapClient("http://hostname.com/webservice",
array(
'cache_wsdl' => WSDL_CACHE_NONE,
'login' => "username",
'password' => "password"
));
This throws this error:
PHP Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from
'http://hostname.com/webservice' : failed to load external entity
"http://hostname.com/webservice"
I gave it try via CURL:
curl --ntlm -u username:password "http://hostname.com/webservice" --verbose
It works as expected and returned the correct xml.
But again SoapClient doesn't support NTLM authentication.
Does anyone knows anything about PHP Soap+NTLM?
Thanks in advance
I recently had this problem too.
Here's the solution I found:
Create NTLMStream.php with the following contents:
<?php
/*
* Original https://thomas.rabaix.net/blog/2008/03/using-soap-php-with-ntlm-authentication
* Modified by http://blogs.msdn.com/b/freddyk/archive/2010/01/19/connecting-to-nav-web-services-from-php.aspx:
*/
class NTLMStream
{
private $path;
private $mode;
private $options;
private $opened_path;
private $buffer;
private $pos;
public function stream_open($path, $mode, $options, $opened_path) {
$this->path = $path;
$this->mode = $mode;
$this->options = $options;
$this->opened_path = $opened_path;
$this->createBuffer($path);
return true;
}
public function stream_close() {
curl_close($this->ch);
}
public function stream_read($count) {
if(strlen($this->buffer) == 0) {
return false;
}
$read = substr($this->buffer,$this->pos, $count);
$this->pos += $count;
return $read;
}
public function stream_write($data) {
if(strlen($this->buffer) == 0) {
return false;
}
return true;
}
public function stream_eof() {
return ($this->pos > strlen($this->buffer));
}
public function stream_tell() {
return $this->pos;
}
public function stream_flush() {
$this->buffer = null;
$this->pos = null;
}
public function stream_stat() {
$this->createBuffer($this->path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
public function url_stat($path, $flags) {
$this->createBuffer($path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
private function createBuffer($path) {
if($this->buffer) {
return;
}
$this->ch = curl_init($path);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($this->ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch, CURLOPT_USERPWD, USERPWD);
$this->buffer = curl_exec($this->ch);
$this->pos = 0;
}
}
class NTLMSoapClient extends \SoapClient
{
function __doRequest($request, $location, $action, $version, $one_way = 0) {
$headers = array(
'Method: POST',
'Connection: Keep-Alive',
'User-Agent: PHP-SOAP-CURL',
'Content-Type: text/xml; charset=utf-8',
'SOAPAction: "'.$action.'"',
);
$this->__last_request_headers = $headers;
$ch = curl_init($location);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERPWD, USERPWD);
$response = curl_exec($ch);
return $response;
}
function __getLastRequestHeaders() {
return implode("\n", $this->__last_request_headers)."\n";
}
}
Then in your test.php
<?php
define('USERPWD', 'domain\username:password');
require_once("NTLMStream.php");
stream_wrapper_unregister("https");
stream_wrapper_register("https", "NTLMStream");
$params = [
'stream_context' => stream_context_create([
'ssl' => [
'ciphers'=>'RC4-SHA',
'verify_peer'=>false,
'verify_peer_name'=>false,
'allow_self_signed'=>true,
]]),
'cache_wsdl' => WSDL_CACHE_NONE,
'soap_version' => SOAP_1_1,
'trace' => 1,
'connection_timeout' => 180,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS
];
$client = new NTLMSoapClient("https://hostname.com/webservice", $params);
$retVal = $client->ReadMultiple(...
...
For http:// instead of https:// substitute:
stream_wrapper_register("http", "NTLMStream")
stream_wrapper_register("https", "NTLMStream")
This library helped me (I use composer):
https://packagist.org/packages/matejsvajger/ntlm-soap-client
$url = 'URL_TO_WEBSERVICE_WSDL';
$config = new matejsvajger\NTLMSoap\Common\NTLMConfig([
'domain' => 'domain',
'username' => 'username',
'password' => 'password'
]);
$client = new matejsvajger\NTLMSoap\Client($url, $config);
$response = $client->ReadMultiple(['filter'=>[], 'setSize'=>1]);
foreach ($response->ReadMultiple_Result->CRMContactlist as $entity) {
print_r($entity);
}
I am trying to use the ChannelAdvisor REST API in PHP to load a list of stock levels that changed since the last sync. This process is documented here: http://developers.channeladvisor.com/rest/#946
Based on the documentation, I have ran a test in Post Man (chrome rest client) to make sure It's working as intended & it does:
Since the test was successfully, I started to work on the PHP script to interact with the REST API in the same manner and it's not quite working correctly. I am getting the following output:
Bad Request - HTTP Error 400. The request is badly formed.
This is my script so far (I am working with Laravel 4, but it's unrelated to that). The issue is with the curlGET method:
<?php namespace Latheesan\ThirdParty\ChannelAdvisorREST;
class ChannelAdvisorREST {
/**
* ChannelAdvisor base uri
*/
const BASE_URL = 'https://api.channeladvisor.com';
/**
* ChannelAdvisor config data
*/
private $config;
/**
* Class constructor
*/
public function __construct()
{
$this->config = \Config::get('channeladvisor');
}
/**
* Method to load stock updates since last sync.
*
* #param $accountId
* #param $lastSync
* #return array
*/
public function getStockUpdates($accountId, $lastSync)
{
// Anticipate errors
try
{
// Init
$stockUpdates = [];
// Query channel advisor
$stockUpdateResults = self::curlGET($accountId, '/v1/Products?$filter=QuantityUpdateDateUtc gt '. $lastSync);
// TODO: parse $stockUpdateResults into $stockUpdates
// Success
return $this->successResponse($stockUpdateResults);
}
catch (\Exception $ex)
{
// Error response
return $this->errorResponse('Failed to load stock updates - '. $ex->getMessage());
}
}
/**
* Generic method to output error responses.
*
* #param string $message
* #return array
*/
private function errorResponse($message = '')
{
// Error
return [
'IsError' => true,
'ErrorMsg' => $message,
'Data' => ''
];
}
/**
* Generic method to output success responses.
*
* #param $data
* #return array
*/
private function successResponse($data)
{
// Success
return [
'IsError' => false,
'ErrorMsg' => '',
'Data' => $data
];
}
/**
* Method to get access token from rest server.
*
* #param $accountId
* #return string
* #throws \Exception
*/
private function getAccessToken($accountId)
{
// Define cache key
$cache_key = 'CA_REST_ACCESS_TOKEN.'. $accountId;
// Check if there is a cached version of access token
if (\Cache::has($cache_key))
return \Cache::get($cache_key);
// Anticipate errors
try
{
// Call rest api server
$response = self::curlPOST('/oauth2/token', [
'client_id' => $this->config['api_app_id'],
'grant_type' => 'soap',
'scope' => 'inventory',
'developer_key' => $this->config['api_developer_key'],
'password' => $this->config['api_password'],
'account_id' => $accountId
]);
// Check if there was an error
if (isset($response->Message))
throw new \Exception($response->Message);
if (isset($response->error))
throw new \Exception($response->error);
// Check if there was an invalid response
if (!isset($response->access_token) || !isset($response->expires_in))
throw new \Exception('Invalid response - '. json_encode($response));
// Cache server response
\Cache::add($cache_key, $response->access_token, floor($response->expires_in / 60));
// Success
return $response->access_token;
}
catch (\Exception $ex)
{
// Rethrow error
throw new \Exception('Failed to load rest api access token - '. $ex->getMessage());
}
}
/**
* Method to generate a HTTP POST request
*
* #param $endpoint
* #param array $fields
* #return string
* #throws \Exception
*/
private function curlPOST($endpoint, $fields = array())
{
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_USERPWD, $this->config['api_app_id'] .':'. $this->config['api_shared_secret']);
curl_setopt($ch, CURLOPT_URL, self::BASE_URL . $endpoint);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields, '', '&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
// Execute post request
$result = curl_exec($ch);
// Debug error
if ($result === FALSE) {
$curlError = 'Error #'. curl_errno($ch) .':'. htmlspecialchars(curl_error($ch));
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
$curlError .= "\r\nDebug Info: ". htmlspecialchars($verboseLog);
curl_close($ch);
throw new \Exception($curlError);
}
#fclose($verbose);
// Close connection
curl_close($ch);
// Finished
return json_decode($result);
}
/**
* Method to generate HTTP GET request
*
* #param $accountId
* #param $queryString
* #return string
* #throws \Exception
*/
private function curlGET($accountId, $queryString)
{
// Open connection
$ch = curl_init();
// Set the url, query string & access token
curl_setopt($ch, CURLOPT_URL, self::BASE_URL . $queryString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '. self::getAccessToken($accountId)
));
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
// Execute post request
$result = curl_exec($ch);
// TESTING
var_dump($result); exit;
// TESTING
// Debug error
if ($result === FALSE) {
$curlError = 'Error #'. curl_errno($ch) .':'. htmlspecialchars(curl_error($ch));
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
$curlError .= "\r\nDebug Info: ". htmlspecialchars($verboseLog);
curl_close($ch);
throw new \Exception($curlError);
}
#fclose($verbose);
// Close connection
curl_close($ch);
// Finished
return json_decode($result);
}
}
The above is a façade class, so I use it like this:
echo '<pre>';
print_r(ChannelAdvisorREST::getStockUpdates
(
'xxx-xxx-xxx', // accountId
'2016-01-18T11:50:03.000Z' // lastSync utc date & time
));
echo '</pre>';
Any idea why it works in Postman REST Client, but fails in my PHP? I thought I am doing the exact same steps. I tried urlencode the query string also; but that did not work either.
I have solved it (for now) like this and it's working correctly for me. Let me know if there's a better/proper way to do this.
/**
* Method to generate HTTP GET request
*
* #param $accountId
* #param $queryString
* #return string
* #throws \Exception
*/
private function curlGET($accountId, $queryString)
{
// Open connection
$ch = curl_init();
// Set the url, query string & access token
curl_setopt($ch, CURLOPT_URL, self::BASE_URL . self::formatUri($queryString));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '. self::getAccessToken($accountId)
));
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
// Execute post request
$result = curl_exec($ch);
// Debug error
if ($result === FALSE) {
$curlError = 'Error #'. curl_errno($ch) .':'. htmlspecialchars(curl_error($ch));
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
$curlError .= "\r\nDebug Info: ". htmlspecialchars($verboseLog);
curl_close($ch);
throw new \Exception($curlError);
}
#fclose($verbose);
// Close connection
curl_close($ch);
// Finished
return json_decode($result);
}
/**
* Method to format query string
*
* #param $queryString
* #return string
*/
private function formatUri($queryString)
{
return str_replace(
['$', ' '],
['%24', '%20'],
$queryString
);
}