新浪微博 授权机制研究

# -*- coding: cp936 -*-
#python 2.7.10
#xiaodeng
#新浪微博 授权机制研究


#微博开放接口的调用,都需要获取用户的身份认证。目前微博开放平台用户认证鉴权主要采用OAuth2.0。


#基本流程讲解
1、引导需要授权的用户到下面的地址
#https://api.weibo.com/oauth2/authorize?\
client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI


2、如用户同意授权,页面跳转到YOUR_REGISTERED_REDIRECT_URI/?code=CODE
3、获取Access Token
#https://api.weibo.com/oauth2/access_token?\
client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
#其中client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET可以使用basic方式加入header中,返回值
'''
{
    "access_token": "SlAV32hkKG",
    "remind_in": 3600,
    "expires_in": 3600
}
'''
4、使用获得的Access Token调用API




5、案例
import os
import sys
import weibo
import webbrowser
import json,urllib,urllib2


APP_KEY='xxxxxxxx'
APP_SECRET='xxxxxxxxxxxxxxxxxx'
CALLBACK_URL='http://www.cnblogs.com/dengyg200891'#这个是设置回调地址,必须与那个”高级信息“里的一致


#请求用户授权的过程
client = weibo.APIClient(APP_KEY, APP_SECRET,CALLBACK_URL)
#print client


authorize_url = client.get_authorize_url(CALLBACK_URL)
#https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//www.cnblogs.com/dengyg200891&response_type=code&client_id=3707867442



#打开浏览器,需手动找到地址栏中URL里的code字段
webbrowser.open(authorize_url)


#进入到授权页面,如下图,请点击‘授权’——在浏览器地址中可查看到code字段所对应的值。
#code会随时变化,用一段时间发现无效了请及时更换。
#code='08ae262f84ae74fc3dfdc02f98ac12f3'
code=raw_input('请输入code:')



#获得用户授权
r = client.request_access_token(code)
print r
#{'access_token': u'2.00PxVPDEahpvCE5d8093b5a508MXEa', 'expires': 1603888639, 'expires_in': 1603888639, 'uid': u'3712558093'}



#access_token
access_token=r.access_token
expires=r.expires
client.set_access_token(access_token, expires)



#设置accsess_token,client可以直接调用API了



#发消息
client.statuses.update.post(status='通过Python SDK发微博')

 

posted @ 2015-10-31 09:58  Xiao|Deng  阅读(361)  评论(0编辑  收藏  举报