Not able to use Magento REST APIs using OAuth - api

I am using Magento version 1.7.0.2 and trying to use Magento Rest APIs using OAuth Integration.
I have installed OAuth and following is the snippet of code that i have put in root directory of magento and i am running it in web browser by typing http://x.x.x.x:5009/oauth_customer.php
$callbackUrl = "http://x.x.x.x:5009/oauth_customer.php";
$temporaryCredentialsRequestUrl = "http://x.x.x.x:5009/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://x.x.x.x:5009/oauth/authorize';
$accessTokenRequestUrl = "http://x.x.x.x:5009/oauth/token";
$apiUrl = "http://x.x.x.x:5009/api/rest";
$consumerKey = 'yourconsumerkey';
$consumerSecret = 'yourconsumersecret';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/products";
$oauthClient->fetch($resourceUrl);
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
}
} catch (OAuthException $e) {
print_r($e);
}
http://x.x.x.x:5009 is ip address followed 5009 where 5009 is port number specified.
When we run this in the browser, i always get the following error -
Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)
oauth_problem=signature_invalid&debug_sbs=Bya6oE4ujTEEFLVL6Mm04PqTA4g=
I am not able to get this work.
Note - I have generated consumer key and secret key. Not sure of how created user credentials with customer access to REST API Resources fit into the above script.
Also i want to know if we can use magento apis on any non magento site with oAuth integration programatically without the user having to grant access to application each time to generate request token.

You have to generate oauth token first. Follow this http://www.aschroder.com/2012/04/introduction-to-the-magento-rest-apis-with-oauth-in-version-1-7/ then test http://www.magentocommerce.com/api/rest/testing_rest_resources.html
If you dont want authentication you can use curl to get desired data. http://snipplr.com/view/44760/
In url pass valid magento resource url like www.yourwebsite.com/api/rest/products

Related

mautic - I want to add contact in mautic via api

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 :)

google api v3 redirect_uri_mismatch Error

i am try to get google account authentication for my app, but when i choose the account to log in i get the error redirect_uri_mismatch,
at google console i create Client ID for web application
first i try to run the app on local host with the following settings
REDIRECT URIS : http://localhost/myapppath/
but get the same error
also i try to host my app at heroku with the following Client ID for web application settings
but get the same error, i search many times on stackoverflow with no success to find a solution
this is my code, it is a test code to get the uploaded videos of a user
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
session_start();
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* Google Developers Console <https://console.developers.google.com/>
* For more information about using OAuth 2.0 to access Google APIs, please see:
* <https://developers.google.com/youtube/v3/guides/authentication>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$OAUTH2_CLIENT_ID = '42965713xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxercontent.com';
$OAUTH2_CLIENT_SECRET = 'y9AWlbxxxxxxxDqdQwJ';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
// Call the channels.list method to retrieve information about the
// currently authenticated user's channel.
$channelsResponse = $youtube->channels->listChannels('contentDetails', array(
'mine' => 'true',
));
$htmlBody = '';
foreach ($channelsResponse['items'] as $channel) {
// Extract the unique playlist ID that identifies the list of videos
// uploaded to the channel, and then call the playlistItems.list method
// to retrieve that list.
$uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads'];
$playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
'playlistId' => $uploadsListId,
'maxResults' => 50
));
$htmlBody .= "<h3>Videos in list $uploadsListId</h3><ul>";
foreach ($playlistItemsResponse['items'] as $playlistItem) {
$htmlBody .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'],
$playlistItem['snippet']['resourceId']['videoId']);
}
$htmlBody .= '</ul>';
}
} catch (Google_ServiceException $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>My Uploads</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>
What credentials type you choose depends on the application you want to build. 'Client ID for web application' should work fine for you.
The URIs you specify in Redirect URIs have to point to the actual script file, like http://example.com/index.php. I don't think http://example.com is supposed to work.
i found the solution after replacing this line
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
by this
$redirect = 'http://localhost/myappname';
i do not know why it is not working when it take the full path of the redirect class

Google OAuth: No refresh_token

I am trying to use the google-api-php-client to upload videos to Youtube.
Since I need access to only one Youtube channel, not to many users channels, I have to authorize my app one time and store a refresh_token to achieve a not expiring access to the API.
The problem is that I don't get a refresh_token with the $client->getAccessToken()-call.
I only get the following values: token_type, expires_in, id_token, created
I created a "Client ID for web applications" using Google Console and use the following code:
<?php
$OAUTH2_CLIENT_ID = '<my client id>';
$OAUTH2_CLIENT_SECRET = '<my client secret>';
$client = new Google_Client();
$client->setApplicationName('<my app name>');
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('profile email https://www.googleapis.com/auth/youtube');
$client->setState('offline');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
if(isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$accessToken = $client->getAccessToken();
var_dump($accessToken, json_decode($accessToken));
}
else {
$aurl = $client->createAuthUrl();
$aurl = str_replace('approval_prompt=auto', 'approval_prompt=force', $aurl);
echo ''.$aurl.'';
}
As you can see I already use $client->setState('offline') and insert apprival_prompt=force in the authURL.
I also tried to revoke access in my Google account manager multiple times and created a new API project.
Thank you in advance for telling me what I'm doing wrong :)
I think the problem is that $accessToken = $client->getAccessToken(); is a post.
client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
It needs to be posted to Google. When it comes back you should have $_SESSION['token']
Full Untested Example:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$youtube = new Google_Service_YouTube($client);
}
print "Access from google: " . $_SESSION['token'];
?>
Something like this maybe. Sorry I cant test it from here its an edit from some other code. If it doesn't work let me know and I will try and test it tonight.

Google Apps Auth with edu.au domain

I am trying to authentify a domain for google docs scope. This is the url:
https://www.google.com/accounts/AuthSubRequest?next=http%3A%2F%2Fwww.mydomain.edu.au%2Fcomponents%2Fgoogle%2FretrieveToken.php&scope=https%3A%2F%2Fdocs.google.com%2Ffeeds%2F&session=1&secure=0&hd=default
So my domain is: www.mydomain.edu.au
But when makng the request Then i get this answer:
The page you have requested cannot be displayed. Another site was requesting access to your Google Account, but sent a malformed request. Please contact the site that you were trying to use when you received this message to inform them of the error. A detailed error message follows:
The site "http://edu.au" has not been registered.
So its identified as edu.au domain.
Is there a way around this?
Thanx
sample code for uploading document to google docs:
public static function uploadDocs($data = array())
{
if (!self::checkInput($data)) return false;
$data['url'] = Google::docsAPIUrl.'default/private/full'.self::getFolder($data['folderId']);
//"?convert=false"
$headers = Google::getAuthToken();
array_push($headers, Google::getGData());
$contentHeaders = self::getInputHeaders($data);
array_push($headers, 'Content-Length: '.$contentHeaders['length']);
array_push($headers, 'Content-Type: '.$contentHeaders['type']);
array_push($headers, 'Slug: '.Html::win2utf8($data['docTitle']));
if ($data['inputMethod'] == 'File')
{
$data['input'] = ((fread(fopen($data['input'], 'rb'), filesize($data['input']))));
}
$curl = Google::curl($data['url'], null, $data['input'], $headers);
if (Curl::checkCode($curl['code']))
{
return self::parseNewXML($curl['response']);
}
else
{
Google::$error = array('errorCode'=>$curl['code'],'errorString'=>$curl['response']);
return false;
}
}
AuthSub is deprecated. You should be using OAuth 2.0 and Drive API v2.

Error while using REST api in magento

I have set up magento locally in my system using XAMPP
I have created a file in root directory named dm.php with the contents
<?php
/**
* Example of products list retrieve using Customer account via Magento REST API. OAuth authorization is used
*/
$callbackUrl = "http://localhost/dm.php";
$temporaryCredentialsRequestUrl = "http://localhost/mage2/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://localhost/mage2/oauth/authorize';
$accessTokenRequestUrl = 'http://localhost/mage2/oauth/token';
$apiUrl = 'http://localhost/mage2/api/rest';
$consumerKey = 'enhksf7u33p3snubewb6zcq0z9c63bvv';
$consumerSecret = 'p7e835cdcxofokeep749jgzz4l1e306p';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/products";
$oauthClient->fetch($resourceUrl);
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
}
} catch (OAuthException $e) {
print_r($e);
}
But this is giving me the following error
Fatal error: Class 'OAuth' not found in D:\Webserver\xampp\htdocs\dm.php on line 19
Can anybody shed some light on this
Thanks
Since oauth is not possible to install in xampp windows i changed the contents of my dm.php file to this.
<?php
$ch = curl_init('http://localhost/mage2/api/rest/customers');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$customers = curl_exec($ch);
echo $customers;
?>
Now i am getting an error like this
{"messages":{"error":[{"code":403,"message":"Access denied"}]}}
What am i doing wrong?
First of all
Go to magento admin panel System->Webservice->RESt Roles->Guest->Resources Access ->SET ALL
Similarly Go to System->Webservice->RESt Attribute->Guest->Resources Access ->SET ALL
Then Hit this url http://****/chanchal/magento/api/rest/products in web Browser and check what error it shows....
According to me it must show product in your website in xml format.
Please let me know..
EDIT:
I configured a localhost just now and got this output refer the Screenshot. Be sure there is product in your magento.
Similarly follow the above steps for admin,customer then create a Ouath consumer from admin panel , Install RESTClient For Mozilla Firefox And follow Here
These for steps are necessary for the setup..the link might help you..
Authentication Endpoints
1./oauth/initiate - this endpoint is used for retrieving the Request Token.
2./oauth/authorize - this endpoint is used for user authorization (Customer).
3./admin/oauth_authorize - this endpoint is used for user authorization (Admin).
4./oauth/token - this endpoint is used for retrieving the Access Token.
Let me know if you have any issues.
Best of luck
A bit of code modifications will easily solve this error 403 forbidden.
What magento engine does is that it uses the default guest user to provide access to the REST api methods. The guest user does not have much powers so it should be better to change this functionality of magento. There are 2 ways of doing this:
1) Quick and dirty fix: in the file /app/code/core/Mage/Api2/Model/Auth.php, change the value of: DEFAULT_USER_TYPE = 'guest' to DEFAULT_USER_TYPE = 'admin'. In the file /app/code/core/Mage/Api2/Model/Auth/Adapter.php, change this line from return (object) array('type' => Mage_Api2_Model_Auth::DEFAULT_USER_TYPE, 'id' => null); to this:
return (object) array('type' => Mage_Api2_Model_Auth::DEFAULT_USER_TYPE, 'id' => '1');
This way the authentication system will not be broken.
2) Proper and long run fix: Override the two functionalities using the magento overriding mechanism to have a better solution in accordance to magento standards. This way the core files will be intact.
We use this link to install oauth for php. Its good and easy to add extension for php.
install oauth php
I hope it helps to all and would solved 'OAuth' not found fatal error.
I had the same issue and was struggling for a week but just try insatlling new version of xammp or wamp with supports ouath.The better solution was ,I installed Ammps 1.9 and in php5.4 I resolved the extension of oauth but still make sure that you select the proper php for extension oauth is supported (php5.4)
For installing Oauth : http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html
Installing PHP Extension for Oauth :
1. Download php_oauth.dll file and add it under C:\xampp\php\ext\
2. add [PHP_OAUTH] extension=php_oauth.dll in php.ini