how to get values from big commerce using php api - bigcommerce

<?php
/**
*Class to instantiate different api connections
*
* #author Adam Bilsing <adambilsing#gmail.com>
*/
class connection
{
/**
*public and private variables
*
* #var string stores data for the class
*/
static public $path;
static private $user;
static private $token;
static private $headers;
/**
* Sets $_path, $_user, $_token, $_headers upon class instantiation
*
* #param $user, $path, $token required for the class
* #return void
*/
public function __construct($user, $path, $token) {
$path = explode('/api/v2/', $path);
$this->_path = $path[0];
$this->_user = $user;
$this->_token = $token;
$encodedToken = base64_encode($this->_user.":".$this->_token);
$authHeaderString = 'Authorization: Basic ' . $encodedToken;
$this->_headers = array($authHeaderString, 'Accept: application/json','Content-Type: application/json');
}
public static function http_parse_headers( $header )
{
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach( $fields as $field ) {
if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if( isset($retVal[$match[1]]) ) {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
if ($retVal['X-Bc-Apilimit-Remaining'] <= 100) {
sleep(300);
}
}
public function error($body, $url, $json, $type) {
global $error;
if (isset($json)) {
$results = json_decode($body, true);
$results = $results[0];
$results['type'] = $type;
$results['url'] = $url;
$results['payload'] = $json;
$error = $results;
} else {
$results = json_decode($body, true);
$results = $results[0];
$results['type'] = $type;
$results['url'] = $url;
$error = $results;
}
}
/**
* Performs a get request to the instantiated class
*
* Accepts the resource to perform the request on
*
* #param $resource string $resource a string to perform get on
* #return results or var_dump error
*/
public function get($resource) {
$url = $this->_path . '/api/v2' . $resource;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_HTTPGET, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
self::http_parse_headers($headers);
curl_close ($curl);
if ($http_status == 200) {
$results = json_decode($body, true);
return $results;
} else {
$this->error($body, $url, null, 'GET');
}
}
/**
* Performs a put request to the instantiated class
*
* Accepts the resource to perform the request on, and fields to be sent
*
* #param string $resource a string to perform get on
* #param array $fields an array to be sent in the request
* #return results or var_dump error
*/
public function put($resource, $fields) {
$url = $this->_path . '/api/v2' . $resource;
$json = json_encode($fields);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
self::http_parse_headers($headers);
curl_close($curl);
if ($http_status == 200) {
$results = json_decode($body, true);
return $results;
} else {
$this->error($body, $url, $json, 'PUT');
}
}
/**
* Performs a post request to the instantiated class
*
* Accepts the resource to perform the request on, and fields to be sent
*
* #param string $resource a string to perform get on
* #param array $fields an array to be sent in the request
* #return results or var_dump error
*/
public function post($resource, $fields) {
global $error;
$url = $this->_path . '/api/v2' . $resource;
$json = json_encode($fields);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec ($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
self::http_parse_headers($headers);
curl_close ($curl);
if ($http_status == 201) {
$results = json_decode($body, true);
return $results;
} else {
$this->error($body, $url, $json, 'POST');
}
}
/**
* Performs a delete request to the instantiated class
*
* Accepts the resource to perform the request on
*
* #param string $resource a string to perform get on
* #return proper response or var_dump error
*/
public function delete($resource) {
$url = $this->_path . '/api/v2' . $resource;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
self::http_parse_headers($headers);
curl_close ($curl);
if ($http_status == 204) {
return $http_status . ' DELETED';
} else {
$this->error($body, $url, null, 'DELETE');
}
}
}
?>
get('RESOURCE');
$store->delete('RESOURCE');
$store->post('RESOURCE', $fields);
$store->put('RESOURCE', $fields);
?>
If i run these code i m getting error like this
( ! ) Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in D:\wamp\www\Bigcommerce\connection.php on line 39
Notice: Undefined variable: fields in D:\wamp\www\Bigcommerce\singlepage.php on line 5
any one pls help me to solve this problem

Related

Connecting to Unleashed API via Woocommerce

I'm trying to connect Woocommerce to Unleashed and have the code for it below. It consistently fails authorisation. It requires a HMAC-SHA256 signature to be generated.
add_action('init', 'register_product');
function register_product(){
register_post_type('product', [
'label' => 'Products Greyville',
'public' => true,
'capability_type' => 'post'
]);
}
function get_products_from_unleashed(){
$current_page = ( ! empty($_POST['current_page']) ) ? $_POST['current_page'] : 1;
$products = [];
$results = wp_remote_get('https://api.unleashedsoftware.com/products/?page=' . $current_page . '&per_page=50');
}
$apiId = "***";
$apiKey = "***";
function getSignature($request, $key) {
return base64_encode(hash_hmac('sha256', $request, $key, true));
}
function getCurl($id, $key, $signature, $endpoint, $requestUrl, $format) {
global $api;
$curl = curl_init($api . $endpoint . $requestUrl);
curl_setopt($curl, CURLOPT_FRESH_CONNECT, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Content-Type: application/$format",
"Accept: application/$format",
"api-auth-id: $id",
"api-auth-signature: $signature"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
// these options allow us to read the error message sent by the API
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_HTTP200ALIASES, range(400, 599));
return $curl;
}
function get($id, $key, $endpoint, $request, $format) {
$requestUrl = "";
if (!empty($request)) $requestUrl = "?$request";
try {
// calculate API signature
$signature = getSignature($request, $key);
// create the curl object
$curl = getCurl($id, $key, $signature, $endpoint, $requestUrl, $format);
// GET something
$curl_result = curl_exec($curl);
error_log($curl_result);
curl_close($curl);
return $curl_result;
}
catch (Exception $e) {
error_log('Error: ' + $e);
}
}
Please also see: https://apidocs.unleashedsoftware.com/PHP
And: https://apidocs.unleashedsoftware.com/AuthenticationHelp

Whatsapp Cloud Api get Media Object ID

I want to upload the media via Whatsapp cloud API in order to send the media to WhatsApp, I have followed the link below, but having the stated issue.
https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#get-media-id
Array ( [error] => Array ( [message] => (#100) The parameter messaging_product is required. [type] => OAuthException [code] => 100 [fbtrace_id] => AQPftb9Bf343375gQ_QytxNen ) ) 400
My Code is
// #1640191015925.jpg on my root folder
$post = [
'file' => '#1640191015925.jpg;type=image/jpeg',
'messaging_product' => 'whatsapp'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v13.0/Phone-Number-ID/media');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$headers = array();
$YOUR_WHATSAPP_ACCESS_TOKEN = '+++++++';
$headers[] = "Authorization: Bearer $YOUR_WHATSAPP_ACCESS_TOKEN";
$headers[] = "Content-Type: image/jpeg";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = json_decode(curl_exec($ch), true);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//$MEDIA_OBJECT_ID = $result['media'][0]['id']; //MEDIA OBJECT ID
print_r($result);
print_r($httpcode);
?> ```
I had the same issue, after some digging around I wrote this function to upload a file and return the id.
function waFileUploader($token, $file, $senderid){
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
$curlfile = new CURLFile($file, $mime, $name);
$filedata = array("messaging_product"=>"whatsapp", "file" => $curlfile);
$url = 'https://graph.facebook.com/v13.0/' . $senderid . '/media';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER,array("Authorization: Bearer $token", "Content-Type: multipart/form-data"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $filedata);
$r = curl_exec($ch);
curl_close($ch);
$id = json_decode($r, true);
return $id["id"];
}

return error code : 401, No license found for the given deviceId

i have use this api
curl -X POST
https://tracking.api.here.com/v2/token
-H 'Authorization: Bearer {signedRequest}'
my php code is
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://tracking.api.here.com/v2/timestamp');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
$result = json_decode($result);
curl_close($ch);
$timestamp = ($result->timestamp);
$accessKey = $deviceId;
$secret = $deviceSecret;
$url = "https://account.api.here.com/oauth2/token";
$nonce = mt_rand(100000,999999);
$timestamp = $timestamp;
$baseString = "grant_type=client_credentials&oauth_consumer_key=".$accessKey."&oauth_nonce=".$nonce."&oauth_signature_method=HMAC-SHA256&oauth_timestamp=".$timestamp."&oauth_version=1.0";
$workingString = array();
foreach (explode('&', $baseString) as $parameter) {
$parameter = explode('=', $parameter);
$workingString[] = urlencode($parameter[0]).'='.trim(urlencode($parameter[1]));
}
$urlEncodeParamaterString = implode('&', $workingString);
$fullBaseString = "POST&".urlencode($url)."&".urlencode($urlEncodeParamaterString);
$hashKey = $secret.'&';
function encode($data) {
return str_replace(['+', '/'], ['-', '_'], base64_encode($data));
}
function decode($data) {
return base64_decode(str_replace(['-', '_'], ['+', '/'], $data));
}
$binaryKey = decode($hashKey);
$signature = encode(hash_hmac("sha256", $fullBaseString, $binaryKey, true));
$authHeader = "OAuth oauth_consumer_key=".$accessKey.",oauth_signature_method='HMAC-SHA256',oauth_timestamp='".$timestamp."',oauth_nonce=".$nonce.",oauth_version='1.0',oauth_signature=".$signature."";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://tracking.api.here.com/v2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$headers[] = 'Authorization: '.$authHeader;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
echo '';
print_r($result);
output
{
code: 401,
id: "312f56e5-db4f-40f5-807f-c5a0413dd668",
message: "No license found for the given deviceId.",
error: "Timestamp wrong When the request timestamp has a more than 10 second difference from the server time, the x-here-timestamp header with the current server timestamp is added to the response. Incorrect Signature If the OAuth signature is incorrect, the response will be a 401 but without the x-here-timestamp field. "
}
In order to tracking a Device using HERE Tracking Service all you'll need to login and Create your Device ID First.
Please see below getting start documentation.
https://developer.here.com/documentation/tracking/dev_guide/topics/getting-started-1-creating-a-device-licence.html

trying to get a list of product images using php bigcommerce library

I keep getting NULL in my response while trying to pull images for products. Making a request for list of products works fine. I'm using the version 2 of the Bigcommerce API. What am I missing?
My code is below:
$product_id = 82;
$organizationAccount = array(
"username" => "stores/xxxx",
"user_token" => "xxxxx"
);
$resource = 'http://api.bigcommerce.com/stores/xxxx/api/v2/products/'.$product_id.'/images.json';
$response = sendRequest($resource, 'GET', 'user_token'); //This gives null
Send Request function
function sendRequest($url, $method, $userToken, $postFields = null, $queryData = null){
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
if( $method == "PUT" ){
curl_setopt($curlHandle, CURLOPT_HEADER, true);
}
curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, $method);
$httpHeader = array('Content-Type: application/json');
$url = (strpos($url, "http") !== false ) ? str_replace("http", "https", $url) : "https://" . $url;
if ($method == "POST" || $method == "PUT" || $method == "DELETE") {
curl_setopt($curlHandle, CURLOPT_URL, $url);
curl_setopt($curlHandle, CURLOPT_POST, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $postFields);
} elseif ($method == "GET") {
$url = (is_null($queryData)) ? $url : $url . "?" . http_build_query($queryData);
curl_setopt($curlHandle, CURLOPT_URL, $url);
}
if (!is_null($userToken)) {
$httpHeader[] = 'X-Auth-Client: ' . BC_CLIENT_ID; //Client id
$httpHeader[] = 'X-Auth-Token: ' . $userToken;
//curl_setopt($curlHandle);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $httpHeader);
}
$response = curl_exec($curlHandle);
return json_decode($response, true);
}
the mistake was from the endpoint url it is supposed to be
$resource = 'http://api.bigcommerce.com/stores/xxxx/v2/products/'.$product_id.'/images.json';
thanks

Google API for Real Time Information? [duplicate]

Firstly, How would you get Google Alerts information into a database other than to parse the text of the email message that Google sends you?
It seems that there is no Google Alerts API.
If you must parse text, how would you go about parsing out the relevant pieces of the email message?
When you create the alert, set the "Deliver To" to "Feed" and then you can consume the feed XML as you would any other feed. This is much easier to parse and digest into a database.
class googleAlerts{
public function createAlert($alert){
$USERNAME = 'XXXXXX#gmail.com';
$PASSWORD = 'YYYYYY';
$COOKIEFILE = 'cookies.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $COOKIEFILE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $COOKIEFILE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_URL,
'https://accounts.google.com/ServiceLogin?hl=en&service=alerts&continue=http://www.google.com/alerts/manage');
$data = curl_exec($ch);
$formFields = $this->getFormFields($data);
$formFields['Email'] = $USERNAME;
$formFields['Passwd'] = $PASSWORD;
unset($formFields['PersistentCookie']);
$post_string = '';
foreach($formFields as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/ServiceLoginAuth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
if (strpos($result, '<title>') === false) {
return false;
} else {
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts');
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/create');
curl_setopt($ch, CURLOPT_POST, 0);
$result = curl_exec($ch);
//var_dump($result);
$result = $this->getFormFieldsCreate($result);
$result['q'] = $alert;
$result['t'] = '7';
$result['f'] = '1';
$result['l'] = '0';
$result['e'] = 'feed';
unset($result['PersistentCookie']);
$post_string = '';
foreach($result as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/manage');
$result = curl_exec($ch);
if (preg_match_all('%'.$alert.'(?=</a>).*?<a href=[\'"]http://www.google.com/alerts/feeds/([^\'"]+)%i', $result, $matches)) {
return ('http://www.google.com/alerts/feeds/'.$matches[1][0]);
} else {
return false;
}
}
}
private function getFormFields($data)
{
if (preg_match('/(<form.*?id=.?gaia_loginform.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form');
}
}
private function getFormFieldsCreate($data)
{
if (preg_match('/(<form.*?name=.?.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form1');
}
}
private function getInputs($form)
{
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}
}
$alert = new googleAlerts;
echo $alert->createAlert('YOUR ALERT');
It will return link to rss feed of your newly created alert
I found a Google Alerts API here. It's pretty minimal and I haven't tested it.