Python based magento consumer - 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.

Related

Twitter API in PHP using codebird

I need to incorporate twitter feature in a project of mine. Among all the libraries and wrappers, codebird seemed convenient. I tried to do the basic authentication using codes from their example, but upon uploading the files on the server, i cant get to access them at all. It shows error 500 in server and i cant test them on localhost.
the index.php file
<?php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('123456', '1234567'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
session_start();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
the callback.php
<?php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('123456', '1234567'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
if(isset($_SESSION['oauth_token'] && isset($_SESSION['oauth_token_secret']))){
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); // see above
$reply = (array) $cb->statuses_homeTimeline();
print_r($reply);
}
else {
echo 'necessary session variables couldnt be found!';
}
?>
This might be a really noob question as i have only basic knowledge in PHP, but any help would be much appriciated, please.

Twitter oAuth login. How to get getAuthorizeURL(authorize) for first time and (authenticate) once user has granted permissions

I am using Twitter oAuth PHP Library (by Abraham Williams) for login-using-twitter for my web-application.
A.The Code model looks like this:
1.The Callback URL in twitter settings is set to :
http://example.com/entrypoint/twitterlogin.php
2.The twitterlogin.php file
<?PHP
if (empty($_GET['oauth_verifier'])){
$request_token = $twitteroauth->getRequestToken();
$_SESSION['onetime_oauth_token'] = $request_token['oauth_token'];
$_SESSION['onetime_oauth_token_secret'] = $request_token['oauth_token_secret'];
}
if (!empty($_GET['oauth_verifier']) && !empty($_SESSION['onetime_oauth_token']) && !empty($_SESSION['onetime_oauth_token_secret'])) {
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $_SESSION['onetime_oauth_token'], $_SESSION['onetime_oauth_token_secret']);
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
$GoesToDB = $access_token['oauth_token'];
$GoesToDBS = $access_token['oauth_token_secret'];
$user_info = $twitteroauth->get('account/verify_credentials');
$GoesToDBArray = $user_info;
}else{
if ($twitteroauth->http_code == 200) {
//generates ~/authenticate?oauth_token=token
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
//generates ~/authorize?oauth_token=token
//$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token'], false);//when and how to use this
exit(header("refresh:0;url=".$url));
} else {
//some error handler
}
}
?>
B.Expected behavior/results
If the user is first time user then generate authorize url (~/authorize?oauth_token=token)
Once the user has granted the permissions to the application generate authenticate url (~/authenticate?oauth_token=token) for future logins
C.Queries
Is the approach correct for the expected behavior
Do i have ask the user to use authorize url if he is an first time user, else use the authenticate url(similar the signin and signup)
Is there way to check if the user has authorized the application using (onetime_oauth_token or something else)
D.Thanking you in advance :) .. you are a life saviour.
Use this -
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token'],TRUE);

Magento api rest oauth not authorizing consumer

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'];

Trouble with SpringPad API

I'm trying to access date using the Springpad API.
If I use the following link:
http://springpadit.com/api/blocks/all?limit=1&text=HARRY+POTTER
I have no problem getting 2 recent results with the search term "J K Rowlings'.
I wrote the following code to do the same thing after authorizing my server:
$api_url = "http://springpadit.com/api/";
$query = $_GET['query'];
$param = array('limit'=>1, 'text'=>$query);
$temp = http_build_query($param,"","&");
$url = $api_url."blocks/all?".$temp;
session_start();
// In state=1 the next request should include an oauth_token.
// If it doesn't go back to 0
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
$oauth = new OAuth($conskey,$conssec,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$request_token_info = $oauth->getRequestToken($req_url);
$_SESSION['secret'] = $request_token_info['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token'].'&oauth_token_secret='.$_SESSION['secret']);
exit;
} else if($_SESSION['state']==1) {
$oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
$access_token_info = $oauth->getAccessToken($acc_url);
$_SESSION['state'] = 2;
$_SESSION['token'] = $access_token_info['oauth_token'];
$_SESSION['secret'] = $access_token_info['oauth_token_secret'];
}
$oauth->setToken($_SESSION['token'],$_SESSION['secret']);
$oauth->fetch($url);
$json = json_decode($oauth->getLastResponse(),true);
print_r($json['blocks']);
} catch(OAuthException $E) {
print_r($E);
}
This should let you create the same query and retrieve the data by using the following link:
http://xrefpro.com/CRM/index.php?query=HARRY+POTTER
All I get is an empty array for my results. What am I doing wrong here??
The springpad api call "/api/blocks/all" is a global search across all users public data. It does not require auth. There does seem to be a bug with the api that causes that search to not work if you are logged in. You can test this by logging out of springpad and hitting
http://springpadit.com/api/blocks/all
and then try it when logged in.
I imagine what is happening is it is trying to find a block with that text in your own account. I am an employee at springpadit.com, we will look into fixing that bug with global queries. For now though, don't bother with oauth for a global query.
If you want to search your own account, use oauth and query
http://springpadit.com/api/users/me/blocks?limit=1&text=Thor
The response won't have a "blocks" node, so just change the print to
print_r($json);

Passing arguments via POST with PHP/PECL OAuth extension

I'm fairly new to the concept of OAuth and I'm trying to interact with the new Rdio API. I've managed to figure out the authentication using the PECL OAuth functions, but Rdio requires arguments to be passed in via POST and I can't figure out how that is done. The authentication works: the user is bounced to Rdio's site and asked to approve the application, and they are then returned to the site. After that, though, the request making calls to the API fails.
Here's some info on the Rdio API: http://developer.rdio.com/docs/REST/
Here's the code I have for authentication... the lines in italics are what I believe should make the call to the API requesting the method named "currentUser"
$req_url = 'http://api.rdio.com/oauth/request_token';
$authurl = 'https://www.rdio.com/oauth/authorize';
$acc_url = 'http://api.rdio.com/oauth/access_token';
$callback = 'http://localhost/test.php';
$api_url = 'http://api.rdio.com/1';
$conskey = 'vmu7x6u4rk8vae8dn28h';
$conssec = 'GrY7gF';
session_start();
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
$oauth = new OAuth($conskey,$conssec,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$request_token_info = $oauth->getRequestToken($req_url);
$_SESSION['secret'] = $request_token_info['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token'].'&oauth_callback='.urlencode($callback));
exit;
} else if($_SESSION['state']==1) {
$oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
$access_token_info = $oauth->getAccessToken($acc_url);
$_SESSION['state'] = 2;
$_SESSION['token'] = $access_token_info['oauth_token'];
$_SESSION['secret'] = $access_token_info['oauth_token_secret'];
}
$args = "method=currentUser";
$oauth->setToken($_SESSION['token'],$_SESSION['secret']);
$oauth->fetch("$api_url", $args);
$json = json_decode($oauth->getLastResponse());
print_r($json);
} catch(OAuthException $E) {
print_r($E);
}
The message I get back:
Warning: OAuth::fetch(http://api.rdio.com/1?oauth_consumer_key=vmu7x6u4rktv468vae8dn28h&oauth_signature_method=HMAC-SHA1&oauth_nonce=12606272174d85622ad26ce8.80381248&oauth_timestamp=1300587050&oauth_version=1.0&oauth_token=238zec5p4rpcpbfd8j36sjggz3jfsssybhxgcn9kvmmrmdxr3t4f2cnspt4dg5xf&oauth_signature=1mZhJ9AUbi0sm6qhNaAntumAckU%3D) [function.OAuth-fetch]: failed to open stream: HTTP request failed! HTTP/1.0 596
The problem is most likely that the arguments (method=currentUser) aren't being passed via POST properly. Does anyone have any idea how to do this using PECL's OAuth extensions?
In case anyone comes across this looking for the answer, here is what I found works:
To perform a POST OAuth signed request, you need to set the OAuth object to send using POST instead of GET by adding this method before the fetch() method:
$oauth->setAuthType(OAUTH_AUTH_TYPE_FORM);
Even if you're using the OAUTH_HTTP_METHOD_POST parameter in the fetch() method, the OAuth instance itself needs to have setAuthType(OAUTH_AUTH_TYPE_FORM) called on it first.
The code for the specific example I was citing is:
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
$oauth = new OAuth($rdio_conskey,$rdio_conssec,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$request_token_info = $oauth->getRequestToken($rdio_req_url);
$_SESSION['secret'] = $request_token_info['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: '.$rdio_auth_url.'?oauth_token='.$request_token_info['oauth_token'].'&oauth_callback='.$callbackurl);
exit;
} else if($_SESSION['state']==1) {
$oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
$access_token_info = $oauth->getAccessToken($rdio_acc_url);
$_SESSION['state'] = 2;
$_SESSION['token'] = $access_token_info['oauth_token'];
$_SESSION['secret'] = $access_token_info['oauth_token_secret'];
}
$oauth = new OAuth($rdio_conskey, $rdio_conssec, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken($access_token_info['oauth_token'],$access_token_info['oauth_token_secret']);
$oauth->setAuthType(OAUTH_AUTH_TYPE_FORM);
$oauth->fetch($rdio_api_url, array("method" => "currentUser", "extras" => "username"), OAUTH_HTTP_METHOD_FORM);
$json = json_decode($oauth->getLastResponse());
print_r($json);
Using OAUTH_AUTH_TYPE_FORM is only a workaround.
Pecl's oauth extension version 1.2.3 has a bug; getRequestToken and getAccessToken use GET requests instead of POST as the RFC wants.
You can work around this bug by passing OAUTH_HTTP_METHOD_POST as 3rd parameter to getRequestToken and 4th parameter to getAccessToken. Yes, those parameters are undocumented.
Version 1.2.4 of pecl/oauth will default to POST.

Categories