Php Rest API: problem creating an array separated with ampersands - php

I have a doubt: An api requests the following structure:
API endpoint
● Production:
https://api-cbt.mercadolibre.com/api/orders/search/?days=<recentdays>&status=<order_status>&page=
<pageno>&access_token=xxx
● HTTP Method: GET
● Content-type header: content-type:application/json
Consequently I created the following structure:
$variables = [];
$variables['days'] = 10;
$variables['page'] = 1;
$query = $meli->get('/api/orders/search/', $variables, array('access_token' => $token));
but for some reason gives HTTPCODE = 401 (this is because $variables and commas are not been considered properly, I know that because access_token work perfect with other API calls).
My main question is what I have to do in order to produce a result like days=&status=&page=.. Im confused because I expected an array to be considered in that way but its not what is going on in my experience.
EDIT------
About GET:
/**
* Execute a GET Request
*
* #param string $path
* #param array $params
* #param boolean $assoc
* #return mixed
*/
public function get($path, $params = null, $assoc = false) {
$exec = $this->execute($path, null, $params, $assoc);
return $exec;
}
the library is provided by MercadoLibre at https://github.com/mercadolibre/php-sdk/blob/master/Meli/meli.php
thanks in advance..

I would threat access_token as a variable to pass within query string:
$variables = [];
$variables['days'] = 10;
$variables['page'] = 1;
$variables['access_token'] => $token;
$query = $meli->get('/api/orders/search/', $variables)
Looking at get() it seems that third argument should be boolean, not an array.

Related

Argument passed to Shopify\Utils::loadCurrentSession() must be of the type array

I am trying to connect to Shopify Rest Admin API using PHP and I am using Shopify API's PHP library and I initialize successfully like this:
Shopify\Context::initialize(
'key',
'secret',
'scope_1, scope_2',
'https://example.com',
new FileSessionStorage('/tmp/php_sessions'),
'2022-10',
);
But when I try to make a request like this:
$this->test_session = Utils::loadCurrentSession(
$requestHeaders,
$requestCookies,
$isOnline
);
Webhookv2::webhooks(
$this->test_session, // Session
[], // Url Ids
[], // Params
);
I get the following error:
Fatal error: Uncaught TypeError: Argument 1 passed to Shopify\Utils::loadCurrentSession() must be of the type array, null given, called in /www/doc/www.example.com/www/script/index.php on line 45 and defined in /www/doc/www.example.com/www/script/vendor/shopify/shopify-api/src/Utils.php:158 Stack trace: #0 /www/doc/www.example.com/www/script/index.php(45): Shopify\Utils::loadCurrentSession(NULL, NULL, NULL) #1 {main} thrown in /www/doc/www.example.com/www/script/vendor/shopify/shopify-api/src/Utils.php on line 158
What am I missing?
P.S.
The code in the Utils.php file (part of Shopify PHP library) that corresponds to the three session variables above:
/**
* Loads the current user's session based on the given headers and cookies.
*
* #param array $rawHeaders The headers from the HTTP request
* #param array $cookies The cookies from the HTTP request
* #param bool $isOnline Whether to load online or offline sessions
*
* #return Session|null The session or null if the session can't be found
* #throws \Shopify\Exception\CookieNotFoundException
* #throws \Shopify\Exception\MissingArgumentException
*/
public static function loadCurrentSession(array $rawHeaders, array $cookies, bool $isOnline): ?Session
{
$sessionId = OAuth::getCurrentSessionId($rawHeaders, $cookies, $isOnline);
return Context::$SESSION_STORAGE->loadSession($sessionId);
}
The loadCurrentSession method requires $requestHeaders to be an array (docs).
Make sure the $requestHeaders variable you pass as argument is indeed an array. Something like:
$requestHeaders = array(
'api_version' => '2023-01',
'X-Shopify-Access-Token' => 'ACCESS_TOKEN'
);
$requestCookies = array();
$isOnline = true;
$this->test_session = Utils::loadCurrentSession(
$requestHeaders,
$requestCookies,
$isOnline
);

How to get google review reply using PHP my business api?

I am using the PHP Google MyBusiness API for my application. I have business reviews.
Now I want to get any replies related to a particular review. I am able to post a reply, but I want to get replies (responses) for the review using PHP GMB API.
How do I do so?
see developers.google.com in the response you get reviewReply object which holds your reply
{
"reviewId": string,
"reviewer": {
object(Reviewer)
},
"starRating": enum(StarRating),
"comment": string,
"createTime": string,
"updateTime": string,
"reviewReply": {
object(ReviewReply)
},
}
more info
to get the review use the get method of Google_Service_MyBusiness_AccountsLocationsReviews_Resource
class Google_Service_MyBusiness_AccountsLocationsReviews_Resource extends Google_Service_Resource
{
/**
* Returns the specified review. This operation is only valid if the specified
* location is verified. Returns `NOT_FOUND` if the review does not exist, or
* has been deleted. (reviews.get)
*
* #param string $name The name of the review to fetch.
* #param array $optParams Optional parameters.
* #return Google_Service_MyBusiness_Review
*/
public function get($name, $optParams = array())
{
$params = array('name' => $name);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_MyBusiness_Review");
}

Upgrading Facebook API version

I have recently received a Facebook developer notification:
Graph API v2.1 Upgrade Notice
foobarapplication has been making recent API calls to Graph API v2.0,
which will reach the end of the 2-year deprecation window on Monday,
August 8, 2016. Please migrate all calls to v2.1 or higher in order to
avoid potential broken experiences.
We recommend using our new Graph API Upgrade Tool to see which of your
calls are affected by this change as well as any replacement calls in
newer versions. You can also use our changelog to see the full list of
changes.
A year ago I have upgraded Facebook for the given PHP application, by extracting the PHP SDK and changing source-code usages. The login review was successful and there were no serious problems since then. However, the app needs to upgrade from Facebook API 2.0 soon. I have an idea as of how to achieve this, but am not sure whether I am correct. Let us consider the following functionalities:
FacebookRedirectLoginHelper class:
/**
* Stores CSRF state and returns a URL to which the user should be sent to
* in order to continue the login process with Facebook. The
* provided redirectUrl should invoke the handleRedirect method.
*
* #param array $scope List of permissions to request during login
* #param string $version Optional Graph API version if not default (v2.0)
* #param boolean $displayAsPopup Indicate if the page will be displayed as a popup
*
* #return string
*/
public function getLoginUrl($scope = array(), $version = null, $displayAsPopup = false)
{
$version = ($version ?: FacebookRequest::GRAPH_API_VERSION);
$this->state = $this->random(16);
$this->storeState($this->state);
$params = array(
'client_id' => $this->appId,
'redirect_uri' => $this->redirectUrl,
'state' => $this->state,
'sdk' => 'php-sdk-' . FacebookRequest::VERSION,
'scope' => implode(',', $scope)
);
if ($displayAsPopup)
{
$params['display'] = 'popup';
}
return 'https://www.facebook.com/' . $version . '/dialog/oauth?' .
http_build_query($params, null, '&');
}
/**
* Returns a URL to which the user should be sent to re-request permissions.
*
* #param array $scope List of permissions to re-request
* #param string $version Optional Graph API version if not default (v2.0)
*
* #return string
*/
public function getReRequestUrl($scope = array(), $version = null)
{
$version = ($version ?: FacebookRequest::GRAPH_API_VERSION);
$this->state = $this->random(16);
$this->storeState($this->state);
$params = array(
'client_id' => $this->appId,
'redirect_uri' => $this->redirectUrl,
'state' => $this->state,
'sdk' => 'php-sdk-' . FacebookRequest::VERSION,
'auth_type' => 'rerequest',
'scope' => implode(',', $scope)
);
return 'https://www.facebook.com/' . $version . '/dialog/oauth?' .
http_build_query($params, null, '&');
}
FacebookRequest class:
/**
* FacebookRequest - Returns a new request using the given session. optional
* parameters hash will be sent with the request. This object is
* immutable.
*
* #param FacebookSession $session
* #param string $method
* #param string $path
* #param array|null $parameters
* #param string|null $version
* #param string|null $etag
*/
public function __construct(
FacebookSession $session, $method, $path, $parameters = null, $version = null, $etag = null
)
{
$this->session = $session;
$this->method = $method;
$this->path = $path;
if ($version) {
$this->version = $version;
} else {
$this->version = static::GRAPH_API_VERSION;
}
$this->etag = $etag;
$params = ($parameters ?: array());
if ($session
&& !isset($params["access_token"])) {
$params["access_token"] = $session->getToken();
}
if (FacebookSession::useAppSecretProof()
&& !isset($params["appsecret_proof"])) {
$params["appsecret_proof"] = $this->getAppSecretProof(
$params["access_token"]
);
}
$this->params = $params;
}
FacebookCurlHttpClient class:
/**
* Detect versions of Curl which report incorrect header lengths when
* using Proxies.
*
* #return boolean
*/
private static function needsCurlProxyFix()
{
$ver = self::$facebookCurl->version();
$version = $ver['version_number'];
return $version < self::CURL_PROXY_QUIRK_VER;
}
My idea is as follows:
getLoginUrl is called from the application; a version of 2.6. should be specified from now on
I do not really use getReRequestUrl, so I will not make changes in the code for it
FacebookRequest will be instantiated with a $version of 2.6
needsCurlProxyFix will be left as it is
Basically, I will use the PHP lib released in 2014, but with specifying $version at calls. Is my approach feasible, or should I use a new client-side library?
As things turned out, my version was up to date and I did not need to do any changes for Facebook's upgrade to version 2.1. except changing the version name used.

PHP implementation of Bitstamp API

I am trying to implement a PHP API to bitstamp to do a re-occurring transaction by placing the PHP code in the crontab.
I am trying to cause the API to communicate with bitstamp to buy X amount of BTC per execution (and then control the frequency from the crontab), this should be the very definition of the basic implementation.
Here is the joy, I am absolutely not a PHP coder. The guys at BX Media were nice enough to post their PHP frame on github: (https://github.com/willmoss/bitstamp-php-api).
However, the way I understand what they have done is that I must create the "parent" PHP to then include their API code which would also include my credentials
So I put together the most basic PHP code
<?php
require('bitstamp.php');
$KEY = 'XXXXXXXXXXXXXXXX';
$SECRET = 'XXXXXXXXXXXXXXXX';
$CLIENT_ID = 'XXXXX';
$bs = new Bitstamp("KEY","SECRET","CLIENT_ID");
// print_r($bs->ticker());
$bs->buyBTC(0.01); // buy 0.01 bitcoins at ask price
//$bs->bitstamp_query("buy", array('amount'=>'0.05','price'=>'50'));
?>
note: that "bitstamp.php" is in the same directory and is what is presently on Github.
<?php
/**
* #package Bitstamp API
* #author https://bxmediaus.com - BX MEDIA - PHP + Bitcoin. We are ready to work on your next bitcoin project. Only high quality coding. https://bxmediaus.com
* #version 0.1
* #access public
* #license http://www.opensource.org/licenses/LGPL-3.0
*/
class Bitstamp
{
private $key;
private $secret;
private $client_id;
public $redeemd; // Redeemed code information
public $withdrew; // Withdrawal information
public $info; // Result from getInfo()
public $ticker; // Current ticker (getTicker())
public $eurusd; // Current eur/usd
/**
* Bitstamp::__construct()
* Sets required key and secret to allow the script to function
* #param Bitstamp API Key $key
* #param Bitstamp Secret $secret
* #return
*/
public function __construct($key, $secret, $client_id)
{
if (isset($secret) && isset($key) && isset($client_id))
{
$this->key = $key;
$this->secret = $secret;
$this->client_id = $client_id;
} else
die("NO KEY/SECRET/CLIENT ID");
}
/**
* Bitstamp::bitstamp_query()
*
* #param API Path $path
* #param POST Data $req
* #return Array containing data returned from the API path
*/
public function bitstamp_query($path, array $req = array())
{
// API settings
$key = $this->key;
// generate a nonce as microtime, with as-string handling to avoid problems with 32bits systems
$mt = explode(' ', microtime());
$req['nonce'] = $mt[1] . substr($mt[0], 2, 6);
$req['key'] = $key;
$req['signature'] = $this->get_signature($req['nonce']);
// generate the POST data string
$post_data = http_build_query($req, '', '&');
// any extra headers
$headers = array();
// our curl handle (initialize if required)
static $ch = null;
if (is_null($ch))
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT,
'Mozilla/4.0 (compatible; MtGox PHP client; ' . php_uname('s') . '; PHP/' .
phpversion() . ')');
}
curl_setopt($ch, CURLOPT_URL, 'https://www.bitstamp.net/api/' . $path .'/');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// run the query
$res = curl_exec($ch);
if ($res === false)
throw new \Exception('Could not get reply: ' . curl_error($ch));
$dec = json_decode($res, true);
if (!$dec)
throw new \Exception('Invalid data received, please make sure connection is working and requested API exists');
return $dec;
}
/**
* Bitstamp::ticker()
* Returns current ticker from Bitstamp
* #return $ticker
*/
function ticker() {
$ticker = $this->bitstamp_query('ticker');
$this->ticker = $ticker; // Another variable to contain it.
return $ticker;
}
/**
* Bitstamp::eurusd()
* Returns current EUR/USD rate from Bitstamp
* #return $ticker
*/
function eurusd() {
$eurusd = $this->bitstamp_query('eur_usd');
$this->eurusd = $eurusd; // Another variable to contain it.
return $eurusd;
}
/**
* Bitstamp::buyBTC()
*
* #param float $amount
*/
function buyBTC($amount){
if (!isset($ticker))
$this->ticker();
$ticker = $this->ticker;
return $this->bitstamp_query('buy', array('amount' => $amount, 'price' => $ticker['ask']));
}
/**
* Bitstamp::sellBTC()
*
* #param float $amount
* #param float $price
* #param string $currency
*/
function sellBTC($amount){
if (!isset($ticker))
$this->ticker();
$ticker = $this->ticker;
return $this->bitstamp_query('sell', array('amount' => $amount, 'price' => $ticker['bid']));
}
/**
* Bitstamp::get_signature()
* Compute bitstamp signature
* #param float $nonce
*/
private function get_signature($nonce)
{
$message = $nonce.$this->client_id.$this->key;
return strtoupper(hash_hmac('sha256', $message, $this->secret));
}
}
I am getting a failure on the execution. As the author of the Bitstamp API has it apparently working with his clients, I assume the error is on my "parent" PHP code. (Note: I am using the real key and secret on my local version).
Anyone have any experience with this API or in general or suggestions?
I'm not sure if this is just anonymization or the actual code, so let me know if I have this wrong, but you have this line:
$bs = new Bitstamp("KEY","SECRET","CLIENT_ID");
This passes the actual strings "KEY", "SECRET", and "CLIENT_ID" to the function; what you want to do is pass the variables you defined on the lines above, like this:
$bs = new Bitstamp($KEY,$SECRET,$CLIENT_ID);
As the author of this api (I am CEO of Bx Media):
You need to remake the constructor like this:
$bs = new Bitstamp("put your key here","put your secret here","put your client ID here");
Ie. you actually put your key/secret/ID between the speech marks.
In PHP, when you put a $ sign, it sets something as a variable.
See more information here: http://www.w3schools.com/php/php_variables.asp
If you want to use variables, you can also use IMSoP's solution.
Please note, we also updated the library tonight with some new functions. So please update your repo to the latest commit to get the new code.
Cheers!

Facebook PHP SDK for Graph API

Is it possible to print to my log files the exact request from Facebook PHP SDK to the Facebook Graphs Server?
Can someone explain me how to modify the Facebook PHP Library https://github.com/facebook/php-sdk
I found:
/**
* Invoke the Graph API.
*
* #param String $path the path (required)
* #param String $method the http method (default 'GET')
* #param Array $params the query/post data
* #return the decoded response object
* #throws FacebookApiException
*/
protected function _graph($path, $method = 'GET', $params = array()) {
if (is_array($method) && empty($params)) {
$params = $method;
$method = 'GET';
}
$params['method'] = $method; // method override as we always do a POST
$result = json_decode($this->_oauthRequest(
$this->getUrl('graph', $path),
$params
), true);
// results are returned, errors are thrown
if (is_array($result) && isset($result['error'])) {
$this->throwAPIException($result);
}
return $result;
}
You should rather have a look at the makeRequest function where the actual http request takes place. Since I wouldn't play around in the api, you could also extend the class and override the method:
class FacebookLogger extends Facebook {
protected function makeRequest($url, $params, $ch=null) {
var_dump($url);
var_dump($params);
parent::makeRequest($url, $params, $ch);
}
}

Categories