doukai2839 2016-04-25 18:10
浏览 58

基于Python的magento消费者

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:

  1. User goes to magentosetup.html and enters consumer token,secret and their magento instance url. They submit this form
  2. 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.
  3. 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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 微信会员卡接入微信支付商户号收款
    • ¥15 如何获取烟草零售终端数据
    • ¥15 数学建模招标中位数问题
    • ¥15 phython路径名过长报错 不知道什么问题
    • ¥15 深度学习中模型转换该怎么实现
    • ¥15 HLs设计手写数字识别程序编译通不过
    • ¥15 Stata外部命令安装问题求帮助!
    • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
    • ¥15 TYPCE母转母,插入认方向
    • ¥15 如何用python向钉钉机器人发送可以放大的图片?