I use the following code to obtain the access token of Google oAuth2.
There is an issue that if I don't add a line to refresh the token with assertion it would return nothing.
Moreover, this refresh token won't work, because when I use this token to access Google Coordinate it returned the 500 Backend Error.
Please correct me.
<?
// codes for getting access token
require_once ('/libs/google-api/src/Google_Client.php');
define('OAUTH2_CLIENT_ID', "MyClientID.apps.googleusercontent.com");
define('SERVICE_ACCOUNT_NAME', "MyEmail#developer.gserviceaccount.com");
define('KEY_FILE', 'f3dc516e866bb9fd42f58f9675d2ed57502d4093-privatekey.p12');
define('EMAIL', 'myEmail');
$key = file_get_contents(KEY_FILE);
$client = new Google_Client();
$client->setApplicationName("test");
$auth=new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/coordinate'),
$key
);
$client->setClientId(OAUTH2_CLIENT_ID);
$client->setAssertionCredentials($auth);
if($client->getAuth()->isAccessTokenExpired()){
$client->getAuth()->refreshTokenWithAssertion(); // if I didn't add this line it would return nothing
}
$accessToken=$client->getAccessToken();
?>
<?
// Errors of access to Google Coordinate using refresh token
stdClass Object
(
[error] => stdClass Object
(
[errors] => Array
(
[0] => stdClass Object
(
[domain] => global
[reason] => backendError
[message] => Backend Error
)
)
[code] => 500
[message] => Backend Error
)
)
?>
<?
// The refresh token received
{
"access_token":"ya29.1.AADtN_U0EDt_5lGMWWbBSOJActF4qEmVwiQ6EyPpEzrHy_ZUoyw7HxYmsgo-sXt1qPzcce9r8hmbviCKB-zQZMAqiO9-4gWxepbsc5jR7ceSgRRR07QvIIYgFZFoFjYCdg",
"expires_in":3600,
"created":1394837729
}
?>
Since you're receiving an acfess_token it is very unlikely that the error is in the authorization steps. Moreover, the correct answer for any Google API to an invalid token is to supply HTTP error code 401. So it appears to me as if the error is in your usage of the Coordinate API.
Related
I get a 401/Not Authorized return for my JTW using PHP with Apple's App Store Connect API.
Using php 7.1.3, I've tried various libraries and raw php (code below). I'm pretty sure the header and payload are fine and the problem is the signing of it, using the p8 private key file I downloaded from Apple. I have quadruple checked the kid, iss, and private key file.
// Create token header as a JSON string
$header = json_encode([
'typ' => 'JWT',
'alg' => 'ES256',
'kid' => '1234567980'
]);
// Create token payload as a JSON string
$payload = json_encode([
'iss' => '12345678-1234-1234-1234-123456789012',
'exp' => time()+60*10, // 20 minute max allowed
'aud' => 'appstoreconnect-v1'
]);
$base64UrlHeader = rtrim(strtr(base64_encode($header), '+/', '-_'), '=');
$base64UrlPayload = rtrim(strtr(base64_encode($payload), '+/', '-_'), '=');
$privateKey = openssl_pkey_get_private('file://'.resource_path('/assets/AppleKey_1234567980.p8'));
$signature = '';
openssl_sign("$base64UrlHeader.$base64UrlPayload", $signature, $privateKey, 'sha256');
// Encode Signature to Base64Url String
$base64UrlSignature = rtrim(strtr(base64_encode($signature), '+/', '-_'), '=');
// Create JWT
$jwt = "$base64UrlHeader.$base64UrlPayload.$base64UrlSignature";
When I submit this to Apple via curl, I get a 401/Not Authorized with details "Authentication credentials are missing or invalid" and nothing more specific.
Has anyone used Apple's App Store Connect API with PHP - google searches have slim to no results I can find.
You can check this solution. i manage to get authenticated and get data from appleconnect. https://stackoverflow.com/a/57150060/860353
I want to add contact in mautic via an API. Below I have the code, but it's not adding the contact in mautic.
I have installed mautic in localhost. Studied the API form in the mautic documentation and tried to do it for at least 2 days, but I am not getting any results on it.
<?php
// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';
use Mautic\Auth\ApiAuth;
session_start();
$publicKey = '';
$secretKey = '';
$callback = '';
// ApiAuth->newAuth() will accept an array of Auth settings
$settings = array(
'baseUrl' => 'http://localhost/mautic', // Base URL of the Mautic instance
'version' => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
'clientKey' => '1_1w6nrty8k9og0kow48w8w4kww8wco0wcgswoow80ogkoo0gsks', // Client/Consumer key from Mautic
'clientSecret' => 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c', // Client/Consumer secret key from Mautic
'callback' => 'http://localhost/mtest/process.php' // Redirect URI/Callback URI for this script
);
/*
// If you already have the access token, et al, pass them in as well to prevent the need for reauthorization
$settings['accessToken'] = $accessToken;
$settings['accessTokenSecret'] = $accessTokenSecret; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenExpires; //UNIX timestamp
$settings['refreshToken'] = $refreshToken;
*/
// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
/*
if( $auth->getAccessTokenData() != null ) {
$accessTokenData = $auth->getAccessTokenData();
$settings['accessToken'] = $accessTokenData['access_token'];
$settings['accessTokenSecret'] = 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c'; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenData['expires']; //UNIX timestamp
$settings['refreshToken'] = $accessTokenData['refresh_token'];
}*/
// Initiate process for obtaining an access token; this will redirect the user to the $authorizationUrl and/or
// set the access_tokens when the user is redirected back after granting authorization
// If the access token is expired, and a refresh token is set above, then a new access token will be requested
try {
if ($auth->validateAccessToken()) {
// Obtain the access token returned; call accessTokenUpdated() to catch if the token was updated via a
// refresh token
// $accessTokenData will have the following keys:
// For OAuth1.0a: access_token, access_token_secret, expires
// For OAuth2: access_token, expires, token_type, refresh_token
if ($auth->accessTokenUpdated()) {
$accessTokenData = $auth->getAccessTokenData();
echo "<pre>";
print_r($accessTokenData);
echo "</pre>";
//store access token data however you want
}
}
} catch (Exception $e) {
// Do Error handling
}
use Mautic\MauticApi;
//use Mautic\Auth\ApiAuth;
// ...
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
$apiUrl = "http://localhost/mautic/api";
$api = new MauticApi();
$contactApi = $api->newApi("contacts", $auth, $apiUrl);
$data = array(
'firstname' => 'Jim',
'lastname' => 'Contact',
'email' => 'jim#his-site.com',
'ipAddress' => $_SERVER['REMOTE_ADDR']
);
$contact = $contactApi->create($data);
echo "<br/>contact created";
Any help will be appreciated.
use Curl\Curl;
$curl = new Curl();
$un = 'mayank';
$pw = 'mayank';
$hash = base64_encode($un.':'.$pw);
$curl->setHeader('Authorization','Basic '.$hash);
$res = $curl->post(
'http://mautic.local/api/contacts/new',
[
'firstname'=>'fn',
'lastname'=>'ln',
'email'=>'t1#test.com'
]
);
var_dump($res);
This is something very simple i tried and it worked for me, please try cleaning cache and enable logging, unless you provide us some error it's hard to point you in right direction. Please check for logs in app/logs directory as well as in /var/logs/apache2 directory.
In my experience sometimes after activating the API in the settings the API only starts working after clearing the cache.
Make sure you have activated the API in the settings
Clear the cache:
cd /path/to/mautic
rm -rf app/cache/*
Then try again
If this didn't work, try to use the BasicAuth example (You have to enable this I the settings again and add a new User to set the credentials)
I suspect that the OAuth flow might be disturbed by the local settings / SSL configuration.
these steps may be useful:
make sure API is enabled(yes I know it's might be obvious but still);
check the logs;
check the response body;
try to send it as simple json via Postman
it may be one of the following problems:
Cache;
You are not sending the key:value; of the required custom field;
you are mistaken with authentication;
Good luck :)
I have created the new user on the CoSign server. I am getting the following response (User password expired) while logging using the ValidateCredentials method.
Array
(
[Success] =>
[ErrData] => Array
(
[Message] => User password expired.
[Module] => ValidateCredentials
[Code] => -36
[InnerCode] => -1878916637
)
)
Can anybody help?
This error means that the user’s password has expired, and you need to reset it
I am using Magento 1.9.2 vesrion for. Using below code for calling rest api.
public function indexAction() {
//Basic parameters that need to be provided for oAuth authentication
//on Magento
$params = array(
'siteUrl' => 'http://127.0.0.1:8080/magentodemo/',
'requestTokenUrl' => 'http://127.0.0.1:8080/magentodemo/oauth/initiate',
'accessTokenUrl' => 'http://127.0.0.1:8080/magentodemo/oauth/token',
'authorizeUrl' => 'http://127.0.0.1:8080/magentodemo/admin/oauth_authorize',//This URL is used only if we authenticate as Admin user type
'consumerKey' => 'c359b57d0d069a336db94fa4aabd61ce',//Consumer key registered in server administration
'consumerSecret' => '2ef029c871b7c013619cc15445a83c25',//Consumer secret registered in server administration
'callbackUrl' => 'http://127.0.0.1:8080/magentodemo/restconnect/index/callback',//Url of callback action below
);
// Initiate oAuth consumer with above parameters
$consumer = new Zend_Oauth_Consumer($params);
// Get request token
$requestToken = $consumer->getRequestToken();
// Get session
$session = Mage::getSingleton('core/session');
// Save serialized request token object in session for later use
$session->setRequestToken(serialize($requestToken));
// Redirect to authorize URL
$consumer->redirect();
return;
}
public function callbackAction() {
//oAuth parameters
$params = array(
'siteUrl' => 'http://127.0.0.1:8080/magentodemo/',
'requestTokenUrl' => 'http://127.0.0.1:8080/magentodemo/oauth/initiate',
'accessTokenUrl' => 'http://127.0.0.1:8080/magentodemo/oauth/token',
'consumerKey' => 'c359b57d0d069a336db94fa4aabd61ce',
'consumerSecret' => '2ef029c871b7c013619cc15445a83c25'
);
// Get session
$session = Mage::getSingleton('core/session');
// Read and unserialize request token from session
$requestToken = unserialize($session->getRequestToken());
// Initiate oAuth consumer
$consumer = new Zend_Oauth_Consumer($params);
// Using oAuth parameters and request Token we got, get access token
$acessToken = $consumer->getAccessToken($_GET, $requestToken);
// Get HTTP client from access token object
$restClient = $acessToken->getHttpClient($params);
// Set REST resource URL
$restClient->setUri('http://127.0.0.1:8080/magentodemo/api/rest/products');
// In Magento it is neccesary to set json or xml headers in order to work
$restClient->setHeaders('Accept', 'application/json');
// Get method
$restClient->setMethod(Zend_Http_Client::GET);
//Make REST request
$response = $restClient->request();
// Here we can see that response body contains json list of products
Zend_Debug::dump($response);
return;
}
Getting below error every time
a:5:{i:0;s:83:"Could not retrieve a valid Token response from Token URL:
oauth_problem=nonce_used";i:1;s:1453:"#0 D:\xampp\htdocs\magentodemo\lib\Zend\Oauth\Http.php(190): Zend_Oauth_Http->_assessRequestAttempt(Object(Zend_Http_Response))
#1 D:\xampp\htdocs\magentodemo\lib\Zend\Oauth\Http.php(191): Zend_Oauth_Http->startRequestCycle(Array)
#2 D:\xampp\htdocs\magentodemo\lib\Zend\Oauth\Http.php(191): Zend_Oauth_Http->startRequestCycle(Array)
#3 D:\xampp\htdocs\magentodemo\lib\Zend\Oauth\Http\RequestToken.php(51): Zend_Oauth_Http->startRequestCycle(Array)
#4 D:\xampp\htdocs\magentodemo\lib\Zend\Oauth\Consumer.php(115): Zend_Oauth_Http_RequestToken->execute()
#5 D:\xampp\htdocs\magentodemo\app\code\local\Test\RestConnect\controllers\IndexController.php(52): Zend_Oauth_Consumer->getRequestToken()
#6 D:\xampp\htdocs\magentodemo\app\code\core\Mage\Core\Controller\Varien\Action.php(418): Test_RestConnect_IndexController->indexAction()
#7 D:\xampp\htdocs\magentodemo\app\code\core\Mage\Core\Controller\Varien\Router\Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('index')
#8 D:\xampp\htdocs\magentodemo\app\code\core\Mage\Core\Controller\Varien\Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#9 D:\xampp\htdocs\magentodemo\app\code\core\Mage\Core\Model\App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
#10 D:\xampp\htdocs\magentodemo\app\Mage.php(684): Mage_Core_Model_App->run(Array)
#11 D:\xampp\htdocs\magentodemo\index.php(83): Mage::run('', 'store')
#12 {main}";s:3:"url";s:31:"/magentodemo/restconnect/index/";s:11:"script_name";s:22:"/magentodemo/index.php";s:4:"skin";s:7:"default";}
I have already created, REST Role for Admin and Assigned to one of the admin user, REST Attribute for Admin, REST Consumers is also created.
Any help will be appreciated.
There was a small fix for above issue. But it takes my 1 day to fix it. In my system apache was running on 8080 port. There is issue in magento oauth to read port while URI validation.
I have stopped other service (IIS or Skype), in my case it was IIS. and port apache on 80. This is the default port.
Hope this will help to someone!!!
$shopify = shopify\client( $shop, $app_settings->api_key, $shop_data->access_token, false );
$products = $shopify('GET', '/admin/products.json', array('published_status' => 'published'));`
I am getting the following response by printing the $shopify:
Closure Object
(
[static] => Array
(
[base_uri] => https://4f4b14c3eb5464ae238dd6cf4b88bce6:c2608b7067c5bf96028876023114b68c#pilibaba.myshopify.com/
[oauth_token] => c2608b7067c5bf96028876023114b68c
[private_app] => 2f996f1bd2a0f4fb343703555c89a234
)
[parameter] => Array
(
[$method_uri] =>
[$query] =>
[$payload] =>
[&$response_headers] =>
[$request_headers] =>
[$curl_opts] =>
)
)
after that accessing the $product i am getting the following error.
Fatal error:
Uncaught phpish\shopify\CurlException: [3] malformed in /*****/shopify_app/shopify_app.php on line 36 thrown in /******/shopify_app/shopify.php on line 67
Is it a problem with my access token? as i do have all the store permission while installing the app.
I did research for this error by didnt find any help either from shopify support team.
change keys of your url:
apikey = c2608b7067c5bf96028876023114b68c
access_token = 4f4b14c3eb5464ae238dd6cf4b88bce6
https://c2608b7067c5bf96028876023114b68c:4f4b14c3eb5464ae238dd6cf4b88bce6#pilibaba.myshopify.com/admin/shop.json