I have already installed php extension for oauth and added it into the php.ini file.Although when i tried to access the OAuth it gives me fatal error as OAuth class not found.
I have added line like extension=oauth.so in php.ini file.
Error Log
PHP Fatal error: Class 'OAuth' not found in /home/artcon/public_html/devsource/webservice/getCategories.php on line 8
Code :
<?php
$callbackUrl = "http://yourhost/oauth_admin.php";
$temporaryCredentialsRequestUrl = "http://yourhost/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://yourhost/admin/oAuth_authorize';
$accessTokenRequestUrl = 'http://yourhost/oauth/token';
$apiUrl = 'http://yourhost/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, array(), 'GET', array('Content-Type' => 'application/json'));
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
}
} catch (OAuthException $e) {
print_r($e->getMessage());
echo "<br/>";
print_r($e->lastResponse);
}
Please help
The error says that the OAuthClass is not found which means a php class that is required by you php scripts is not found.
What you did in php.ini is to enable php OAuth extension. Even if the extension is enabled if you do use a php class in a php script and that class is not defined anytwhere you might get a php fatal error.
Did you restart your webserver (apache/nginx) after adding that line in php.ini? If you have just added it without restart, the changes are not in effect. Use a service httpd restart (centos) or service apache2 restart (ubuntu/debian) or a service nginx restart if you use nginx and see how it plays.
Related
I'm getting this error (I'm using PHP 7.0 and Google PHP API 2.9.1, and I'm using OAuth credentials for Web application):
Uncaught Error: Class 'Google_Service_Gmail_Resource_Users' not found in /google-api-2.9.1/vendor/google/apiclient-services/src/Google/Service/Gmail.php:106
Stack trace:
#0 /public_html/oauth2callback.php(20): Google_Service_Gmail->__construct(Object(Google\Client))
#1 {main} thrown in /public_html/googe-api-2.9.1/vendor/google/apiclient-services/src/Google/Service/Gmail.php on line 106
And here is what Im trying to do:
My index.php:
<?php
include_once __DIR__ . '/google-api-2.9.1/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . 'credenciales.json');
$client->addScope(Google_Service_Gmail::GMAIL_READONLY);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$gmail = new Google_Service_Gmail($client);
$user = 'me';
$list = $gmail->users_messages->listUsersMessages($user, [ 'q' => ['from:someEmail#gmail.com in:inbox'], ]);
$messageList = $list->getMessages();
$inboxMessage = [];
foreach($messageList as $mlist){
$optParamsGet2['format'] = 'full';
$single_message = $gmail->users_messages->get('me',$mlist->id, $optParamsGet2);
$message_id = $mlist->id;
$headers = $single_message->getPayload()->getHeaders();
$snippet = $single_message->getSnippet();
foreach($headers as $single) {
if ($single->getName() == 'Subject') {
$message_subject = $single->getValue();
}
else if ($single->getName() == 'Date') {
$message_date = $single->getValue();
$message_date = date('M jS Y h:i A', strtotime($message_date));
}
else if ($single->getName() == 'From') {
$message_sender = $single->getValue();
$message_sender = str_replace('"', '', $message_sender);
}
}
$inboxMessage[] = [
'messageId' => $message_id,
'messageSnippet' => $snippet,
'messageSubject' => $message_subject,
'messageDate' => $message_date,
'messageSender' => $message_sender
];
echo json_encode($inboxMessage);
}
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
My oauth2callback.php file:
<?php
require_once __DIR__ . '/google-api-2.9.1/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . 'credenciales.json');
$client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Gmail::GMAIL_READONLY);
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$gmail = new Google_Service_Gmail($client);
$user = 'me';
$list = $gmail->users_messages->listUsersMessages($user, [ 'q' => ['from:someEmail#gmail.com in:inbox'], ]);
$messageList = $list->getMessages();
$inboxMessage = [];
foreach($messageList as $mlist){
$optParamsGet2['format'] = 'full';
$single_message = $gmail->users_messages->get('me',$mlist->id, $optParamsGet2);
$message_id = $mlist->id;
$headers = $single_message->getPayload()->getHeaders();
$snippet = $single_message->getSnippet();
foreach($headers as $single) {
if ($single->getName() == 'Subject') {
$message_subject = $single->getValue();
}
else if ($single->getName() == 'Date') {
$message_date = $single->getValue();
$message_date = date('M jS Y h:i A', strtotime($message_date));
}
else if ($single->getName() == 'From') {
$message_sender = $single->getValue();
$message_sender = str_replace('"', '', $message_sender);
}
}
$inboxMessage[] = [
'messageId' => $message_id,
'messageSnippet' => $snippet,
'messageSubject' => $message_subject,
'messageDate' => $message_date,
'messageSender' => $message_sender
];
echo json_encode($inboxMessage);
}
}
When I accept the app, google takes me to:
https://mywebsite.com/oauth2callback.php?code=4/8521e-kahsd875CLzcbtvppohs584ehtptRa6nXZpjhbFTDGFQjN9jgvQj_7be2E2j654ytv&scope=https://www.googleapis.com/auth/gmail.readonly
So, I go get pass the authorization screen from Google, I accept my app, and then a blank screen. The error shown comes from the error log file.
Why I get that Class 'Google_Service_Gmail_Resource_Users' is not found when I do call the autoload file?
So I see a few problems with your current setup. The one relating to your problem is that you aren't using Composer. It's small and simple and easy to use, and handles all the autoloading stuff for you. No worries about missing directories or unzipping errors. The download version of the Google API client already includes a pre-built Composer vendor folder, so you aren't saving any disk space or code complexity by skipping it.
Second is your directory structure; the way your server is set up, it's trivial for someone to access https://mywebsite.example.com/credenciales.json and get your private data.
So here's what I recommend:
In your document root (/var/www/html/home_dir) create a public folder and copy index.php and oauth2callback.php to that folder.
Update your server configuration to point to /var/www/html/home_dir/public as your document root
Change into /var/www/html/home_dir and run composer require google/apiclient (install Composer if you haven't already)
Edit your PHP files as needed, adjusting the path to credentiales.json and changing your require directives to point to /var/www/html/home_dir/vendor/autoload.php.
In extension to my question - https://stackoverflow.com/q/36847384/658209
I was thinking of using OAuth1Session from requests_oauthlib to retrieve access token and access token secret value. I want to do something similar to what is being done in below example:
<?php
/**
* Example of OAuth authorization n using Admin account via Magento REST API.
*/
$callbackUrl = "http://yourhost/oauth_admin.php";
$temporaryCredentialsRequestUrl = "http://magentohost/oauth/initiate?oauth_callback=" .
urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://magentohost/admin/oauth_authorize';
$accessTokenRequestUrl = 'http://magentohost/oauth/token';
$apiUrl = 'http://magentohost/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']) {68
$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);
echo "oauth_token:".$accessToken['oauth_token']."<br/>";
echo "oauth_token_secret:".$accessToken['oauth_token_secret'];
exit;
} else {
echo "authorisation failed";
}
} catch (OAuthException $e) {
print_r($e);
}
I have come up with the following code:
class Magento_Oauth_Admin(restful.Resource):
def get(self):
return render_template('magentosetup.html')
def post(self):
consumer_key=request.form.get('consumer_key')
consumer_secret=request.form.get('consumer_secret')
magentourl=request.form.get('magentourl')
session['magentourl']=magentourl
callbackurl = api.url_for(Magento_Access_Token)
temporary_credentials_request_url = '{magentourl}/oauth/initiate?{callbackurl}'.format(magentourl, urllib.urlencode(
dict(oauth_callback=callbackurl)))
admin_authorization_url = '{magentourl}/admin/oauth_authorize'.format(magentourl)
oauth_session = OAuth1Session(consumer_key, client_secret=consumer_secret, callback_uri=callbackurl)
# First step, fetch the request token.
fetch_response = oauth_session.fetch_request_token(temporary_credentials_request_url)
session['resource_owner_key'] = fetch_response.get('oauth_token')
session['resource_owner_secret'] = fetch_response.get('oauth_token_secret')
# Second step. Follow this link and authorize
authorization_url = oauth_session.authorization_url(admin_authorization_url)
return redirect(authorization_url)
class Magento_Access_Token(restful.Resource):
""" The user has been redirected back from the provider to the registered
callback URL. With this redirection comes an authorization code included
in the redirect URL. We will use that to obtain an access token."""
def get(self):
access_token_request_url = '{magentourl}/oauth/token'.format(session['magentourl'])
verifier = request.args.get('oauth_verifier')
oauth = OAuth1Session(consumer_key,
client_secret=consumer_secret,
resource_owner_key=session['resource_owner_key'],
resource_owner_secret=session['resource_owner_secret'],
verifier=verifier)
oauth_tokens = oauth.fetch_access_token(access_token_request_url)
resource_owner_key = oauth_tokens.get('oauth_token')
resource_owner_secret = oauth_tokens.get('oauth_token_secret')
return render_template('magentosetupcomplete.html')
api.add_resource(Magento_Oauth_Admin,"/v2/generateaccesstoken/",endpoint="generateaccesstoken")
api.add_resource(Magento_Access_Token,"/v2/callback/",endpoint="callback")
I am not sure how to handle callback and redirects instead of asking the user to go to authorization_url and then paste the redirect url
EDIT: After reading Robbie's comment I have updated my code and split it into 2 endpoints. So now flow of my application is something like:
User goes to magentosetup.html and enters consumer token,secret and their magento instance url. They submit this form
We get the credentials from above form into Magento_Oauth_Admin post and then we trigger the oAuth dance to generate access token and secret.
Once the access token is generated I will store it somewhere(not written that code here)
My question now is in the final step (after the provider redirects user to consumer API, after user authorization), will I be able to redirect the user to magentosetupcomplete.html by using return render_template('magentosetupcomplete.html') to confirm to the user that the access token has been generated and saved. I am asking this because the /callback endpoint has been called from magento. I am not sure what the flow of control is in this situation.
This question already has answers here:
Magento Rest API Oauth URL Returning 404
(5 answers)
Closed 8 years ago.
When following the documentation from here
http://www.magentocommerce.com/api/rest/introduction.html
The sample code below 404s when it tries to make the calls to the urls /oauth/initiate and
/admin/oauth_authorize.
/api/rest works fine, as I have the current rule in .htaccess
RewriteRule ^api/rest api.php?type=rest [QSA,L]
Is there other rules I am missing? It was my understanding the magento REST api should work out the box. Or could the issue be unrelated to url rewrites?
I have created the appropriate REST Roles and Attributes and placed the consumer key/secret inside the sample code also but no dice.
Just to clarify, a guest role works fine when hitting api/rest using a rest client or browser. However trying to set up authentication with the below sample code is causing me issues for the above reasons.
<?php
/**
* Example of simple product POST using Admin account via Magento REST API. OAuth authorization is used
*/
$callbackUrl = "http://yourhost/oauth_admin.php";
$temporaryCredentialsRequestUrl = "http://magentohost/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://magentohost/admin/oauth_authorize';
$accessTokenRequestUrl = 'http://magentohost/oauth/token';
$apiUrl = 'http://magentohost/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";
$productData = json_encode(array(
'type_id' => 'simple',
'attribute_set_id' => 4,
'sku' => 'simple' . uniqid(),
'weight' => 1,
'status' => 1,
'visibility' => 4,
'name' => 'Simple Product',
'description' => 'Simple Description',
'short_description' => 'Simple Short Description',
'price' => 99.95,
'tax_class_id' => 0,
));
$headers = array('Content-Type' => 'application/json');
$oauthClient->fetch($resourceUrl, $productData, OAUTH_HTTP_METHOD_POST, $headers);
print_r($oauthClient->getLastResponseInfo());
}
} catch (OAuthException $e) {
print_r($e);
} ?>
Does this part $callbackUrl = "http://yourhost/oauth_admin.php"; works? If if it is not working, fix this. Remember to replace value http://yourhost/oauth_admin.php with right value and try in your browser first.
Make sure that both yourhost and magentohost local or both remote server. For example if your magentohost is remote server and yourhost is local, redirection will fail and you will get 404 error.
I'm attempting to connect to my magento api from an external server but i'm having an issue with OAuth.
I've created a consumer in the backend, assigned what it can access, authorized the consumer through oauth using terminal and it gave me my token and token secret.
My PHP is as follows;
<?php
$hostUrl = 'redacted';
$callbackUrl = $hostUrl."oauth_customer.php";
$temporaryCredentialsRequestUrl = $hostUrl."oauth/initiate?oauth_callback=".urlencode($callbackUrl);
$adminAuthorizationUrl = $hostUrl."oauth/authorize";
$accessTokenRequestUrl = $hostUrl."oauth/token";
$apiUrl = $hostUrl."api/rest";
$consumerKey = 'redacted';
$consumerSecret = 'redacted';
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, array(), 'GET', array('Content-Type' => 'application/json'));
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
}
} catch (OAuthException $e) {
print_r($e->getMessage());
echo "<br/>";
print_r($e->lastResponse);
}
?>
When I run this php file it redirects me to the magento site and says;
AUTHORIZE APPLICATION
consumer_name requests access to your account
After authorization application will have access to you account.
Authorize | Reject
When I click "Authorize" it redirects me to a 404 within magento. If I return to the php file it will redirect me to that same "authorize application" page over and over again.
I already have the token and such so I assume that it should already be authorized.
I'm attempting to access the name of products as well as their inventory quantity so I can't simply use guest access. Any help would be greatly appreciated.
Your callback URL should not be on the remote host, it should be on your application's host.
Remove $callbackUrl row and exchange with this code:
$callbackUrl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
I have consumer key and secret. I tried to get oauth request token using consumer key and secret but my bad i'm getting error which is
Uncaught exception 'OAuthException' with message 'Invalid auth/bad
request (got a 404, expected HTTP/1.1 20X or a redirect)'
i've tried the below code to get the request token, but it did not work
$callbackUrl = "http://www.myhost.com/oauth_admin.php";
$temporaryCredentialsRequestUrl = "http://www.myhost.com/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://www.myhost.com/admin/oauth_authorize';
$accessTokenRequestUrl = 'http://www.myhost.com/oauth/token';
$apiUrl = 'http://www.myhost.com/api/rest';
$consumerKey = 'my consumerKey';
$consumerSecret = 'my consumerSecret';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
$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']) && !isset($_SESSION['state'])) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
echo $_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if (isset($_SESSION['state']) && $_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;
}
print_r($_SESSION);//get this by next page
Any help would be great!
I solved that by changing the server configurations to assume the .htaccess rules. Try to check it out.