JWT Server Authentication Signature validation failed for BOX in PHP - php

I'm facing the issue with validation of JWT Signature in PHP.
Here is my code
// Create token header as a JSON string
$header = ["alg" => "RS256",
"typ" => "JWT",
"kid" => "gnkp02u2"];
$header = json_encode((object) $header);
// Create token payload as a JSON string
$payload = [
"typ" => "jwt",
"kid" => "gnkp02u2",
"iss" => "op63g1amchcxy456oei2tkfk1lg4dbxy",
"aud" => "https://api.box.com/oauth2/token",
"jti" => "4f1g23a12aa854rtyuil",
"exp" => time() + 30,
"sub" => "23527187",
"box_sub_type" => "enterprise"];
$payload = json_encode((object) $payload);
// Encode Header to Base64Url String
$base64UrlHeader = str_replace(["+", "/", "="], ["-", "_", ""],
base64_encode($header));
// Encode Payload to Base64Url String
$base64UrlPayload = str_replace(["+", "/", "="], ["-", "_", ""],
base64_encode($payload));
$headerPayload = $base64UrlHeader . "." . $base64UrlPayload;
//$headerPayload = base64_encode($header) . "." . base64_encode($payload);
// Create Signature Hash
$privateKey = "file://private.key";
try{
$privateKeyResource = openssl_get_privatekey($privateKey,
"73bed4ee2b994f5fdf0ddef660d8f935");
$result = openssl_sign($headerPayload, $signature, $privateKeyResource, OPENSSL_ALGO_SHA256);
if ($result === false)
{
var_dump($result);
throw new RuntimeException("Failed to generate signature: ".implode("\n", getOpenSSLErrors()));
}
$signatureEncoded = base64_encode($signature);
$jwt = "$base64UrlHeader.$base64UrlPayload.$signatureEncoded";
}
catch(Exception $e){
print_r($e->getMessage());
}
print_r( $jwt );`
And it generates
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Imdua3AwMnUyIn0.eyJ0eXAiOiJqd3QiLCJraWQiOiJnbmtwMDJ1MiIsImlzcyI6Im9wNjNnMWFtY2hjeHk0NTZvZWkydGtmazFsZzRkYnh5IiwiYXVkIjoiaHR0cHM6XC9cL2FwaS5ib3guY29tXC9vYXV0aDJcL3Rva2VuIiwianRpIjoiNGYxZzIzYTEyYWE4NTRydHl1aWwiLCJleHAiOjE1MjIwODI5OTUsInN1YiI6IjIzNTI3MTg3IiwiYm94X3N1Yl90eXBlIjoiZW50ZXJwcmlzZSJ9.JMH1sXHrAsT9dURJF/5sOgl2k+qFX/wiqwER4RZwdtxLkLDXDJTzFGZuLPW8JMKqdzntc9hIdc/RHQOla2mi4s1WiGEj/9T1gBPWhjTd4kiZgEenLsZUuLFG77wlzdNPQnm3jON7kM08EfQZU+YYhGDF6JVJ2yH31zkJZqucdbg9Ne43OYPMKEmfa1bKJ3/QmLZXHIEgTYGhh78RsbzViJq3wCqWtUOmksDxCz7/400ZDrmQRH1JIEJW1W6A1oAjPEJVSTniw6a60VVTDXW3WUI0TN68CG5PuNzTXEJcBgnfr1J4yVWeat4rArEyOFsLoyOgBSIu0IHcMRo/V4Md4w==
And I'm using this assertion in curl like this
$ curl https://api.box.com/oauth2/token -d 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&client_id=op63g1amchcxy456oei2tkfk1lg4dbxy&client_secret=R7MGxLa7dAZfz5YbXMMPf6a6m8OcYZ2K&assertion=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Imdua3AwMnUyIn0.eyJ0eXAiOiJqd3QiLCJraWQiOiJnbmtwMDJ1MiIsImlzcyI6Im9wNjNnMWFtY2hjeHk0NTZvZWkydGtmazFsZzRkYnh5IiwiYXVkIjoiaHR0cHM6XC9cL2FwaS5ib3guY29tXC9vYXV0aDJcL3Rva2VuIiwianRpIjoiNGYxZzIzYTEyYWE4NTRydHl1aWwiLCJleHAiOjE1MjIwODI5OTUsInN1YiI6IjIzNTI3MTg3IiwiYm94X3N1Yl90eXBlIjoiZW50ZXJwcmlzZSJ9.JMH1sXHrAsT9dURJF/5sOgl2k+qFX/wiqwER4RZwdtxLkLDXDJTzFGZuLPW8JMKqdzntc9hIdc/RHQOla2mi4s1WiGEj/9T1gBPWhjTd4kiZgEenLsZUuLFG77wlzdNPQnm3jON7kM08EfQZU+YYhGDF6JVJ2yH31zkJZqucdbg9Ne43OYPMKEmfa1bKJ3/QmLZXHIEgTYGhh78RsbzViJq3wCqWtUOmksDxCz7/400ZDrmQRH1JIEJW1W6A1oAjPEJVSTniw6a60VVTDXW3WUI0TN68CG5PuNzTXEJcBgnfr1J4yVWeat4rArEyOFsLoyOgBSIu0IHcMRo/V4Md4w==' -X POST
And in response I'm getting this error
{"error":"invalid_grant","error_description":"Signature verification error. The public key identified by \"kid\" must correspond to the private key used for signing."}
Even kid is given and correct
I don't know what I'm doing wrong

I've solved Box JWT Token issue by using https://github.com/firebase/php-jwt repository, and this is working fine.
use \Firebase\JWT\JWT;
class BoxApi
{
public $authorize_url = 'https://account.box.com/api/oauth2/authorize';
public $token_url = 'https://api.box.com/oauth2/token';
public $api_url = 'https://api.box.com/2.0';
public $upload_url = 'https://upload.box.com/api/2.0';
public $access_token;
public $filename;
public $passPhrase;
public $clientId;
public $clientSecret;
public $accessType;
public $accessTypeId;
public $publicKeyId;
public function __construct($filename, $passPhrase, $clientId, $clientSecret, $accessType = "enterprise", $accessTypeId, $publicKeyId)
{
$this->filename = $filename;
$this->passPhrase = $passPhrase;
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
$this->accessType = $accessType;
$this->accessTypeId = $accessTypeId;
$this->publicKeyId = $publicKeyId;
self::getAccessToken();
}
/* Get AccessToken by JWT*/
public function getAccessToken()
{
$private_key_file = $this->filename;
$fp = fopen ($private_key_file, "r");
if (!$fp)
{
die("Unable to open file");
}
$raw_key_data = fread ($fp, filesize ($private_key_file));
fclose ($fp);
$privateKey = openssl_get_privatekey($raw_key_data , $this->passPhrase);
define("FIREBASE_PRIVATE_KEY", $privateKey);
$token = array(
"iss" => $this->clientId,
"aud" => "https://api.box.com/oauth2/token",
"jti" => sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
),
"exp" => time() + 30,
"sub" => $this->accessTypeId,
"box_sub_type" => $this->accessType
);
$jwt = JWT::encode($token, FIREBASE_PRIVATE_KEY, 'RS256', $this->publicKeyId);
$params = 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&client_id=' . $this->clientId . '&client_secret=' . $this->clientSecret . '&assertion=' . $jwt;
$token = json_decode(self::httpClient("POST", $this->token_url, $params), true);
print "<pre>";
print_r($token);
print "</pre>";
$this->access_token = $token["access_token"];
}
/* Sets the required before biulding the query */
private function set_opts(array $opts)
{
if (!array_key_exists('access_token', $opts)) {
$opts['access_token'] = $this->access_token;
}
return $opts;
}
/* Builds the URL for the call */
private function build_url($api_func, array $opts = array(), $url = null)
{
print "build uri";
$opts = $this->set_opts($opts);
if (isset($url)) {
$base = $url . $api_func . '?';
} else {
$base = $this->api_url . $api_func . '?';
}
$query_string = http_build_query($opts);
$base = $base . $query_string;
return $base;
}
/* Uploads a file */
public function put_file($filename, $parent_id)
{
$file = defined('PHP_MAJOR_VERSION') && PHP_MAJOR_VERSION >= 5 ? new CurlFile(realpath($filename)) : '#/' . realpath($filename);
$url = $this->build_url('/files/content', array(), $this->upload_url);
$params = array('filename' => $file, 'name' => basename($filename), 'parent_id' => $parent_id, 'access_token' => $this->access_token);
return json_decode($this->httpClient("post", $url, $params), true);
}
/* Create a new folder */
public function create_folder($name, $parent_id)
{
$url = $this->build_url("/folders");
$params = array('name' => $name, 'parent' => array('id' => $parent_id));
return json_decode($this->httpClient("post", $url, json_encode($params)), true);
}
/* Modifies the folder details as per the api */
public function update_folder($folder, array $params)
{
$url = $this->build_url("/folders/$folder");
return json_decode($this->httpClient("put", $url, $params), true);
}
/* Shares a folder */
public function share_folder($folder, array $params)
{
$url = $this->build_url("/folders/$folder");
return json_decode($this->httpClient("put", $url, $params), true);
}
/* Shares a file */
public function share_file($file, array $params)
{
$url = $this->build_url("/files/$file");
return json_decode($this->httpClient("put", $url, $params), true);
}
/* Curl Api calls */
private static function httpClient($method, $url, $params = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if (strcasecmp($method, "POST") == 0) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
} elseif (strcasecmp($method, "PUT") == 0) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
} elseif (strcasecmp($method, "DELETE") == 0) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
}
?>

Related

WordPress - Issues with referencing custom PHP class in functions.php

I apologize if this is really dumb/obvious but this is my first experience working with classes in WordPress.
I made a class called SharpSpringService.php inside my custom plugin sharpspring-form. I placed the class within a classes folder within that custom plugin for organization purposes.
I'm referencing the SharpSpringService class within a function in functions.php but am getting an error. When I declare a new instance of SharpSpringService and place the account ID and secret key as parameters, I get a message: "Expected SharpSpring, got string". I also see an Internal Server 500 Error in the Chrome dev consoles that seems to be a result of creating an instance of this class.
I'm not sure why the parameters are expected to be "SharpSpring" as they should be accountID and secretkey.
Here is the SharpSpringService class:
private $authError = false;
private $accountID = null;
private $secretKey = null;
/**
* SharpSpringService constructor.
* #param $accountID SharpSpring Account ID
* #param $secretKey SharpSpring Secret Key
*/
public function __construct($accountID, $secretKey)
{
$this->accountID = $accountID;
$this->secretKey = $secretKey;
}
public function hasAuthError() {
return $this->authError;
}
public function makeCall($method, $params = []) {
$requestID = session_id();
$accountID = $this->accountID;
$secretKey = $this->secretKey;
$data = array(
'method' => $method,
'params' => $params,
'id' => $requestID,
);
$queryString = http_build_query([
'accountID' => $accountID,
'secretKey' => $secretKey
]);
$url = "http://api.sharpspring.com/pubapi/v1/?$queryString";
$data = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
));
$result = curl_exec($ch);
curl_close($ch);
$resultObj = json_decode($result);
if ($resultObj->error != null) {
throw new \Exception($result->error);
}
return $resultObj;
}
}
And here is the function in functions.php that is referencing the class:
function get_memberships_callback(){
$newsListID = 550280195;
$listName = "NewsList";
$contactEmail = $_POST['contactemail'];
$sharpSpringService = new SharpSpringService('[redacted]', '[redacted]'); //this is where the code chokes
$return = [];
if($contactEmail != null && $contactEmail !=""){
$lists = $sharpSpringService->makeCall('getListMemberships', [
'emailAddress' => $contactEmail,
]);
if (count($lists) > 0) {
$listArray = json_decode(json_encode($lists), true);
$inNewsList = false;
foreach($listArray as $list){
if($list = $newsListID){
//the user is subscribed to the news list
$inNewsList = true;
$converted_result = ($inNewsList) ? 'true' : 'false';
}
}
}
$return[] = array(
"status" => $converted_result,
"list" => $listName
);
return json_encode($return);
}
else{
return $return;
}
die();
}
For calling numerous files, it is sometimes convenient to define a constant:
define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
include( MY_PLUGIN_PATH . 'includes/admin-page.php');
include( MY_PLUGIN_PATH . 'includes/classes.php');

Call Sharepoint WebService with PHP SoapClient

I extended the PHP SoapClient to use it with NTLM Sharepoint Authentication:
class NTLMSoapClient extends SoapClient {
function __doRequest($request, $location, $action, $version) {
$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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
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_USERPWD, $this->user . ':' . $this->password);
$response = curl_exec($ch);
return $response;
}
function __getLastRequestHeaders() {
return implode("n", $this->__last_request_headers) . "n";
}
public final function __call($methodName, array $methodParams) {
/*
* Is soapClient set? This check may look double here but in later
* developments it might help to trace bugs better and it avoids calls
* on wrong classes if $soapClient got set to something not SoapClient.
*/
if (!$this->soapClient instanceof \SoapClient) {
// Is not set
throw new \Exception('Variable soapClient is not a SoapClient class, have: ' . gettype($this->soapClient), 0xFF);
}
// Is it a "SOAP callback"?
if (substr($methodName, 0, 2) == '__') {
// Is SoapClient's method
$returned = call_user_func_array(array($this->soapClient, $methodName), $methodParams);
} else {
// Call it
$returned = $this->soapClient->__call($methodName, $methodParams);
}
// Return any values
return $returned;
}
}
class SPNTLMSoapClient extends NTLMSoapClient {
protected $user = 'xxxxxx';
protected $password = 'xxxxxxx';
}
class NTLMStream {
private $path;
private $mode;
private $options;
private $opened_path;
private $buffer;
private $pos;
public function stream_open($path, $mode, $options, $opened_path) {
echo "[NTLMStream::stream_open] $path , mode=$mode n";
$this->path = $path;
$this->mode = $mode;
$this->options = $options;
$this->opened_path = $opened_path;
$this->createBuffer($path);
return true;
}
public function stream_close() {
echo "[NTLMStream::stream_close] n";
curl_close($this->ch);
}
public function stream_read($count) {
echo "[NTLMStream::stream_read] $count n";
if (strlen($this->buffer) == 0) {
return false;
}
$read = substr($this->buffer, $this->pos, $count);
$this->pos += $count;
return $read;
}
public function stream_write($data) {
echo "[NTLMStream::stream_write] n";
if (strlen($this->buffer) == 0) {
return false;
}
return true;
}
public function stream_eof() {
echo "[NTLMStream::stream_eof] ";
if ($this->pos > strlen($this->buffer)) {
echo "true n";
return true;
}
echo "false n";
return false;
}
/* return the position of the current read pointer */
public function stream_tell() {
echo "[NTLMStream::stream_tell] n";
return $this->pos;
}
public function stream_flush() {
echo "[NTLMStream::stream_flush] n";
$this->buffer = null;
$this->pos = null;
}
public function stream_stat() {
echo "[NTLMStream::stream_stat] n";
$this->createBuffer($this->path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
public function url_stat($path, $flags) {
echo "[NTLMStream::url_stat] n";
$this->createBuffer($path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
/* Create the buffer by requesting the url through cURL */
private function createBuffer($path) {
if ($this->buffer) {
return;
}
echo "[NTLMStream::createBuffer] create buffer from : $pathn";
$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_USERPWD, $this->user . ':' . $this->password);
echo $this->buffer = curl_exec($this->ch);
echo "[NTLMStream::createBuffer] buffer size : " . strlen($this->buffer) . "bytesn";
$this->pos = 0;
}
}
class SPNTLMStream extends NTLMStream {
protected $user = 'xxxxxxx';
protected $password = 'xxxxxxxx';
}
stream_wrapper_unregister('https');
stream_wrapper_register('https', 'SPNTLMStream') or die("Failed to register protocol");
$wsdl = "https://wxxxxxxxxx?WSDL";
$client = new SPNTLMSoapClient($wsdl);
I succesfully call: "print_r($client->__getFunctions())" and get the following:
Array
(
[0] => CopyIntoItemsLocalResponse CopyIntoItemsLocal(CopyIntoItemsLocal $parameters)
[1] => CopyIntoItemsResponse CopyIntoItems(CopyIntoItems $parameters)
[2] => GetItemResponse GetItem(GetItem $parameters)
[3] => CopyIntoItemsLocalResponse CopyIntoItemsLocal(CopyIntoItemsLocal $parameters)
[4] => CopyIntoItemsResponse CopyIntoItems(CopyIntoItems $parameters)
[5] => GetItemResponse GetItem(GetItem $parameters)
)
My Question now is: How do I call these Methods with $client and parameters,
$client->__call('CopyIntoItems', $params) doesnt work
$client->CopyIntoItems($params) doesnt work
I never get any Response.....
Thx in advance....

Shopify private app- php

updated shopify.php
<?php
include('shopify_api_config.php');
class ShopifyClient {
public $shop_domain;
private $token;
private $api_key;
private $secret;
private $last_response_headers = null;
public function __construct($shop_domain, $token, $api_key, $secret) {
$this->name = "ShopifyClient";
$this->shop_domain = 'https://#4ef34cd22b136c1a7b869e77c8ce8b3c:#fb2b17c283a27c65e4461d0ce8e5871b#discountshop-8.myshopify.com';
$this->token = $token;
$this->api_key = '4ef34cd22b136c1a7b869e77c8ce8b3c';
$this->secret = '28cdbeb0b925bba5b8c9a60cfbb8c3cb';
$client = new ShopifyClient($shop_domain, $token, $api_key, $secret);
}
// Get the URL required to request authorization
public function getAuthorizeUrl($scope, $redirect_url='') {
$url = "http://{$this->shop_domain}/admin/oauth/authorize?client_id={$this->api_key}&scope=" . urlencode($scope);
if ($redirect_url != '')
{
$url .= "&redirect_uri=" . urlencode($redirect_url);
}
return $url;
}
// Once the User has authorized the app, call this with the code to get the access token
public function getAccessToken($code) {
// POST to POST https://SHOP_NAME.myshopify.com/admin/oauth/access_token
$url = "https://{$this->shop_domain}/admin/oauth/access_token";
$payload = "client_id={$this->api_key}&client_secret={$this->secret}&code=$code";
$response = $this->curlHttpApiRequest('POST', $url, '', $payload, array());
$response = json_decode($response, true);
if (isset($response['access_token']))
return $response['access_token'];
return '';
}
public function callsMade()
{
return $this->shopApiCallLimitParam(0);
}
public function callLimit()
{
return $this->shopApiCallLimitParam(1);
}
public function callsLeft($response_headers)
{
return $this->callLimit() - $this->callsMade();
}
public function call($method, $path, $params=array())
{
$baseurl = "https://{$this->shop_domain}/";
$url = $baseurl.ltrim($path, '/');
$query = in_array($method, array('GET','DELETE')) ? $params : array();
$payload = in_array($method, array('POST','PUT')) ? stripslashes(json_encode($params)) : array();
$request_headers = in_array($method, array('POST','PUT')) ? array("Content-Type: application/json; charset=utf-8", 'Expect:') : array();
// add auth headers
$request_headers[] = 'X-Shopify-Access-Token: ' . $this->token;
$response = $this->curlHttpApiRequest($method, $url, $query, $payload, $request_headers);
$response = json_decode($response, true);
if (isset($response['errors']) or ($this->last_response_headers['http_status_code'] >= 400))
throw new ShopifyApiException($method, $path, $params, $this->last_response_headers, $response);
return (is_array($response) and (count($response) > 0)) ? array_shift($response) : $response;
}
public function validateSignature($query)
{
if(!is_array($query) || empty($query['signature']) || !is_string($query['signature']))
return false;
foreach($query as $k => $v) {
if($k == 'signature') continue;
$signature[] = $k . '=' . $v;
}
sort($signature);
$signature = md5($this->secret . implode('', $signature));
return $query['signature'] == $signature;
}
private function curlHttpApiRequest($method, $url, $query='', $payload='', $request_headers=array())
{
$url = $this->curlAppendQuery($url, $query);
$ch = curl_init($url);
$this->curlSetopts($ch, $method, $payload, $request_headers);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno) throw new ShopifyCurlException($error, $errno);
list($message_headers, $message_body) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$this->last_response_headers = $this->curlParseHeaders($message_headers);
return $message_body;
}
private function curlAppendQuery($url, $query)
{
if (empty($query)) return $url;
if (is_array($query)) return "$url?".http_build_query($query);
else return "$url?$query";
}
private function curlSetopts($ch, $method, $payload, $request_headers)
{
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_USERAGENT, 'ohShopify-php-api-client');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $method);
if (!empty($request_headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
if ($method != 'GET' && !empty($payload))
{
if (is_array($payload)) $payload = http_build_query($payload);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $payload);
}
}
private function curlParseHeaders($message_headers)
{
$header_lines = preg_split("/\r\n|\n|\r/", $message_headers);
$headers = array();
list(, $headers['http_status_code'], $headers['http_status_message']) = explode(' ', trim(array_shift($header_lines)), 3);
foreach ($header_lines as $header_line)
{
list($name, $value) = explode(':', $header_line, 2);
$name = strtolower($name);
$headers[$name] = trim($value);
}
return $headers;
}
private function shopApiCallLimitParam($index)
{
if ($this->last_response_headers == null)
{
throw new Exception('Cannot be called before an API call.');
}
$params = explode('/', $this->last_response_headers['http_x_shopify_shop_api_call_limit']);
return (int) $params[$index];
}
}
class ShopifyCurlException extends Exception { }
class ShopifyApiException extends Exception
{
protected $method;
protected $path;
protected $params;
protected $response_headers;
protected $response;
function __construct($method, $path, $params, $response_headers, $response)
{
$this->method = $method;
$this->path = $path;
$this->params = $params;
$this->response_headers = $response_headers;
$this->response = $response;
parent::__construct($response_headers['http_status_message'], $response_headers['http_status_code']);
}
function getMethod() { return $this->method; }
function getPath() { return $this->path; }
function getParams() { return $this->params; }
function getResponseHeaders() { return $this->response_headers; }
function getResponse() { return $this->response; }
}
?>
I installed one private app in my shopify store for download csv file, after installed, when click download button, it will display like
Fatal error: Uncaught exception 'ShopifyCurlException' with message 'Could not
resolve host: http:; Host not found' in C:\xampp\htdocs\cat\lib\shopify.php:102
Stack trace: #0 C:\xampp\htdocs\cat\lib\shopify.php(67): ShopifyClient->curlHttpApiRequest('GET', 'https://http://...', Array, Array, Array)
#1 C:\xampp\htdocs\cat\index-oauth.php(26): ShopifyClient->call('GET', 'admin/orders.js...', Array)
#2 {main} thrown in C:\xampp\htdocs\cat\lib\shopify.php on line 102.
I dont know how to fix. If anybody know, please help.
Thank you!.
I had the same problem. Try this.
In your constructor pass the following argument as the $shop_domain.
https:// #apikey:#password#hostname
Replace #apiKey, #password and hostname with your values. Also leave '#' in hostname.
I.e. #yourshop.com
$shop_domain = 'https://#apikey:#password#hostname';
$token = 'your token';
$key = 'your key';
$secret = 'your secret';
$client = new ShopifyClient($shop_domain, $token, $api_key, $secret);

How to get Citrix's Goto Meeting Access Token

Hi i am trying to get Goto meeting OAuth access token via php curl. but it returns nothing when i make a call. please guide me how i can get it, Code is given below.
$api_key = "123456";
$redirect_url = urlencode("URL");
$webinar_url = "https://api.citrixonline.com/oauth/authorize?client_id=".$api_key."&redirect_uri=".$redirect_url;
function getWebinarData($link)
{
$headers = array(
"HTTP/1.1",
"Content-type: application/json",
"Accept: application/json"
);
$curl = curl_init($link);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //2
$response = curl_exec($curl);
echo "<pre>DATA: ";print_r($response);echo "</pre>";
curl_close($curl);
return $response;
}
/**
* goto api
* Author: Ahad Ali
* Date: valentines day 2013
* Classes Curl, OAuth, GotoTraining
*/
define ("API_KEY", "");
define ("REDIRECT_URL","");
define ("AUTH_AUTOLOGIN_URL","https://developer.citrixonline.com/oauth/g2t/authorize.php");
define ("AUTH_EXCHANGE_URL", "https://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code=<CODE>&client_id=" . API_KEY);
define ("MANAGE_TRAINING_URL","https://api.citrixonline.com/G2T/rest/organizers/<ORGANIZERKEY>/trainings");
class Curl
{
public $result;
public function __construct()
{
}
public function request($url, $data="", $method="get", $headers="")
{
$ch = curl_init();
// this is autologiM USING CURL POST
// avoiding the redirect to gotos site where it asks for email and password and redirects back to the URL with a code
curl_setopt($ch, CURLOPT_URL, $url);
if($method == "post")
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, true);
}
if($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$this->result = (string) curl_exec($ch);
curl_close($ch);
return $this->result;
}
public function __destruct()
{
}
}
class OAuth
{
public $autologin_url;
public $exchange_url;
public $code;
public $auth_result;
//https://api.citrixonline.com/oauth/authorize?client_id= used this URL to get all the field names
public $login_data = array(
'emailAddress' => '',
'password' => '',
'client_id' => '',
'access_type'=> 'G2T',
'app_name' => '',
'redirect_uri' => '',
'submitted' => 'form_submitted',
);
public function __construct($autologin_url = AUTH_AUTOLOGIN_URL, $exchange_url = AUTH_EXCHANGE_URL, $apikey=API_KEY)
{
$this->autologin_url = $autologin_url;
$this->exchange_url = $exchange_url;
$this->login_data['client_id'] = $apikey;
}
public function authorize()
{
$this->getCode();
$this->exchangeCodeForAccessToken();
}
public function getCode()
{
$curl = new Curl();
$result = $curl->request($this->autologin_url, $this->login_data, "post");
$arr = explode("\n", $result);
foreach($arr as $k=>$v)
{
if(strstr($v,"Location: http:"))
$return_url = $v;
}
$query = trim(parse_url($return_url, PHP_URL_QUERY));// adds one unnecessary _ (underscore) at the end of the query string
$this->code = substr($query, 5, (strlen($query) - 6));//starting from 5 get me ...number of chars
}
function exchangeCodeForAccessToken()
{
$this->exchange_url = str_replace("<CODE>", $this->code, $this->exchange_url);
$curl = new Curl();
$result = $curl->request($this->exchange_url);
$this->auth_result = json_decode($result);
}
public function __destruct()
{
}
}
class GotoTraining extends OAuth
{
public $manage_training_url;
public $training_result;
public $error_list = array("AuthFailure", "AccessDenied", "ExpiredToken", "InternalError", "InvalidRequest", "InvalidMethod", "MissingToken", "NoSuchTraining", "InvalidToken");
public function __construct($url = MANAGE_TRAINING_URL)
{
$this->manage_training_url = $url;
parent::__construct();
}
/**
*Arguement List for goto CreateTraining service
* [name] => Representational State Transfer 101
[description] => The REST-ful way to APIs.
[timeZone] => America/Los_Angeles
[times] => Array
(
[0] => stdClass Object
(
[startDate] => 2011-09-08T18:25:00Z
[endDate] => 2011-09-08T19:25:00Z
)
[1] => stdClass Object
(
[startDate] => 2011-09-09T18:25:00Z
[endDate] => 2011-09-09T19:25:00Z
)
)
[registrationSettings] => stdClass Object
(
[disableWebRegistration] => false
[disableConfirmationEmail] => false
)
[organizers] => Array
(
[0] => 6512477
[1] => 38712
[2] => 9876466
)
*/
public function createTraining($name, $desc, $times)
{
$registrationSettings["disableWebRegistration"] = "false";
$registrationSettings["disableConfirmationEmail"] = "false";
$json["name"] = $name;
$json["description"] = $desc;
$json["timeZone"] = "Australia/Sydney";
$json["times"] = $times;//array for startDate, endDate
$json["registrationSettings"] = $registrationSettings;
$json["organizers"][0] = $this->auth_result->organizer_key;
$this->manage_training_url = str_replace("<ORGANIZERKEY>", $this->auth_result->organizer_key, $this->manage_training_url);
$json = json_encode($json);
//$post_data[] = "Authorization:OAuth oauth_token=" . $this->auth_result->access_token;
//$this->manage_training_url = $this->manage_training_url . "?oauth_token=" . $this->auth_result->access_token;
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
'Authorization: OAuth oauth_token=' . $this->auth_result->access_token
);
//$this->manage_training_url = $this->manage_training_url . "?oauth_token=" . $this->auth_result->access_token;
$curl = new Curl();
$this->training_result = $curl->request($this->manage_training_url, $json, "post", $headers);
$arr = explode("\n", $this->training_result);
$this->webCode = trim($arr[count($arr)-1], '"');
$this->checkError();
return $this->webCode;
}
public function checkError()
{
foreach($this->error_list as $val)
{
if(strstr($this->training_result, $val))
$this->webCode = $val;
}
return 0;
}
}

Simple Twitter Oauth authorization asking for credentials every time

I am making a simple twitter based login/signup system using the tutorial here. I get the oauth_token as well as oauth token secret every time I get the user to login. However, even when the user is already logged in, he is being asked to login again. I just wanted to know how do I check if the user is already logged in?
Do I need to store the oauth_token and oauth token secret in session? If I do store these in a session, how do i authenticate if they are valid?
The library used has something like this:
<?php
session_start();
class EpiOAuth
{
public $version = '1.0';
protected $requestTokenUrl;
protected $accessTokenUrl;
protected $authorizeUrl;
protected $consumerKey;
protected $consumerSecret;
protected $token;
protected $tokenSecret;
protected $signatureMethod;
public function getAccessToken()
{
$resp = $this->httpRequest('GET', $this->accessTokenUrl);
return new EpiOAuthResponse($resp);
}
public function getAuthorizationUrl()
{
$retval = "{$this->authorizeUrl}?";
$token = $this->getRequestToken();
return $this->authorizeUrl . '?oauth_token=' . $token->oauth_token;
}
public function getRequestToken()
{
$resp = $this->httpRequest('GET', $this->requestTokenUrl);
return new EpiOAuthResponse($resp);
}
public function httpRequest($method = null, $url = null, $params = null)
{
if(empty($method) || empty($url))
return false;
if(empty($params['oauth_signature']))
$params = $this->prepareParameters($method, $url, $params);
switch($method)
{
case 'GET':
return $this->httpGet($url, $params);
break;
case 'POST':
return $this->httpPost($url, $params);
break;
}
}
public function setToken($token = null, $secret = null)
{
$params = func_get_args();
$this->token = $token;
$this->tokenSecret = $secret;
}
public function encode($string)
{
return rawurlencode(utf8_encode($string));
}
protected function addOAuthHeaders(&$ch, $url, $oauthHeaders)
{
$_h = array('Expect:');
$urlParts = parse_url($url);
$oauth = 'Authorization: OAuth realm="' . $urlParts['path'] . '",';
foreach($oauthHeaders as $name => $value)
{
$oauth .= "{$name}=\"{$value}\",";
}
$_h[] = substr($oauth, 0, -1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $_h);
}
protected function generateNonce()
{
if(isset($this->nonce)) // for unit testing
return $this->nonce;
return md5(uniqid(rand(), true));
}
protected function generateSignature($method = null, $url = null, $params = null)
{
if(empty($method) || empty($url))
return false;
// concatenating
$concatenatedParams = '';
foreach($params as $k => $v)
{
$v = $this->encode($v);
$concatenatedParams .= "{$k}={$v}&";
}
$concatenatedParams = $this->encode(substr($concatenatedParams, 0, -1));
// normalize url
$normalizedUrl = $this->encode($this->normalizeUrl($url));
$method = $this->encode($method); // don't need this but why not?
$signatureBaseString = "{$method}&{$normalizedUrl}&{$concatenatedParams}";
return $this->signString($signatureBaseString);
}
protected function httpGet($url, $params = null)
{
if(count($params['request']) > 0)
{
$url .= '?';
foreach($params['request'] as $k => $v)
{
$url .= "{$k}={$v}&";
}
$url = substr($url, 0, -1);
}
$ch = curl_init($url);
$this->addOAuthHeaders($ch, $url, $params['oauth']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = $this->curl->addCurl($ch);
return $resp;
}
protected function httpPost($url, $params = null)
{
$ch = curl_init($url);
$this->addOAuthHeaders($ch, $url, $params['oauth']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params['request']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = $this->curl->addCurl($ch);
return $resp;
}
protected function normalizeUrl($url = null)
{
$urlParts = parse_url($url);
$scheme = strtolower($urlParts['scheme']);
$host = strtolower($urlParts['host']);
$port = intval($urlParts['port']);
$retval = "{$scheme}://{$host}";
if($port > 0 && ($scheme === 'http' && $port !== 80) || ($scheme === 'https' && $port !== 443))
{
$retval .= ":{$port}";
}
$retval .= $urlParts['path'];
if(!empty($urlParts['query']))
{
$retval .= "?{$urlParts['query']}";
}
return $retval;
}
protected function prepareParameters($method = null, $url = null, $params = null)
{
if(empty($method) || empty($url))
return false;
$oauth['oauth_consumer_key'] = $this->consumerKey;
$oauth['oauth_token'] = $this->token;
$oauth['oauth_nonce'] = $this->generateNonce();
$oauth['oauth_timestamp'] = !isset($this->timestamp) ? time() : $this->timestamp; // for unit test
$oauth['oauth_signature_method'] = $this->signatureMethod;
$oauth['oauth_version'] = $this->version;
// encoding
array_walk($oauth, array($this, 'encode'));
if(is_array($params))
array_walk($params, array($this, 'encode'));
$encodedParams = array_merge($oauth, (array)$params);
// sorting
ksort($encodedParams);
// signing
$oauth['oauth_signature'] = $this->encode($this->generateSignature($method, $url, $encodedParams));
return array('request' => $params, 'oauth' => $oauth);
}
protected function signString($string = null)
{
$retval = false;
switch($this->signatureMethod)
{
case 'HMAC-SHA1':
$key = $this->encode($this->consumerSecret) . '&' . $this->encode($this->tokenSecret);
$retval = base64_encode(hash_hmac('sha1', $string, $key, true));
break;
}
return $retval;
}
public function __construct($consumerKey, $consumerSecret, $signatureMethod='HMAC-SHA1')
{
$this->consumerKey = $consumerKey;
$this->consumerSecret = $consumerSecret;
$this->signatureMethod = $signatureMethod;
$this->curl = EpiCurl::getInstance();
}
}
class EpiOAuthResponse
{
private $__resp;
public function __construct($resp)
{
$this->__resp = $resp;
}
public function __get($name)
{
if($this->__resp->code < 200 || $this->__resp->code > 299)
return false;
parse_str($this->__resp->data, $result);
foreach($result as $k => $v)
{
$this->$k = $v;
}
return $result[$name];
}
}
The normal flow dictates that applications send request tokens to oauth/authorize in Twitter's implementation of the OAuth Specification. To take advantage of "Sign in with Twitter", applications should send request tokens received in the oauth_token parameter to oauth/authenticate instead.
(c) https://dev.twitter.com/docs/auth/sign-in-with-twitter
So find where their library (or your code) performs request to /authorize endpoint and replace it with /authenticate
About tokens: as long as you've received user tokens - store it in some persistent storage (database, file, etc) since that tokens are permanent (they will be valid until user haven't revoked them manually).
Enable option "Sign in with Twitter" for application OAuth Settings

Categories