Sina weibo access api (新浪微博接口)

Source:

http://blog.csdn.net/zhanh1218/article/details/26383469

Code:

#!/usr/bin/python 
# -*- coding: utf-8 -*-

'''
Created on 2014-06-28
@author: guaguastd
@name: sinaWeiboLogin.py
'''

import sys 
reload(sys)
#sys.setdefaultencoding("utf8")

from weibo import APIClient

#import webbrowser
import re, json

import urllib, urllib2, urllib3, cookielib
#import hashlib
import base64, rsa, binascii # encrypt

class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
    """
    # Refer to blog:http://www.cnblogs.com/wly923/archive/2013/04/28/3048700.html
    """
    def http_error_301(self, cls, req, fp, code, msg, headers):
        result = urllib2.HTTPRedirectHandler.http_error_301(cls, req, fp, code, msg, headers)
        result.status = code
        return result

    def http_error_302(self, cls, req, fp, code, msg, headers):
        result = urllib2.HTTPRedirectHandler.http_error_302(cls, req, fp, code, msg, headers)
        result.status = code
        return result
    
def get_cookie():
    cookies = cookielib.CookieJar()
    return urllib2.HTTPCookieProcessor(cookies)
   
def get_opener(proxy=False):
    rv=urllib2.build_opener(get_cookie(), SmartRedirectHandler())
    rv.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')]
    return rv

class SinaAPI():
    """
    # Refer to http://blog.csdn.net/zhanh1218/article/details/26383469
    """
    def __init__(self, CALLBACK_URL, APP_KEY, REDIRECT_URL, USER_ID, USER_PSWD):
        self.CALLBACK_URL = CALLBACK_URL
        self.APP_KEY = APP_KEY
        self.REDIRECT_URL = REDIRECT_URL
        self.USER_ID = USER_ID
        self.USER_PSWD = USER_PSWD
        self.http = urllib3.PoolManager()
        
    def get_username(self, USER_ID):
        # The Encryption Algorithm of username 
        # ssologin.js : ah.su=sinaSSOEncoder.base64.encode(m(aj));
        USER_ID_ = urllib.quote(USER_ID) # encode username, avoid error example:@ &  
        su = base64.encodestring(USER_ID_)[:-1]
        return su
   
    def get_password_rsa(self, USER_PSWD, PUBKEY, servertime, nonce):
        # rsa Encrypt :  #when pwencode = "rsa2"
        rsaPubkey = int(PUBKEY, 16)#pubkey from 16 to 10
        key_1 = int('10001', 16) #10001 to 65537 
        key = rsa.PublicKey(rsaPubkey, key_1) #
        message = str(servertime) + "\t" + str(nonce) + "\n" + str(USER_PSWD)
        passwd = rsa.encrypt(message, key)
        passwd = binascii.b2a_hex(passwd) #to 16
        return passwd
      
    def get_parameter(self):
        su = self.get_username(self.USER_ID)
        #su = get_username(USER_ID)‎‎
        url = "https://login.sina.com.cn/sso/prelogin.php?entry=openapi&callback=sinaSSOController.preloginCallBack\
&su="+su+"&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.15)"
        r = self.http.request('GET', url)
        p = re.compile('\((.*)\)')
        json_data = p.search(r.data).group(1)
        data = json.loads(json_data)
        
        PUBKEY = data['pubkey']
        pcid = data['pcid']
        servertime = str(data['servertime'])
        nonce = data['nonce']
        rsakv = str(data['rsakv'])
        sp = self.get_password_rsa(self.USER_PSWD, PUBKEY, servertime, nonce)
        
        #print pcid; print servertime; print nonce; print rsakv; print sp; print su
        return pcid, servertime, nonce, rsakv, sp, su
         
    def get_ticket(self):
        pcid, servertime, nonce, rsakv, sp, su = self.get_parameter()
        fields = urllib.urlencode({
            'entry'        : 'openapi',
            'gateway'      : '1',
            'from'         : '',
            'savestate'    : '0',
            'useticket'    : '1',
            'pagerefer'    :'',
            'pcid'         : pcid,
            'ct'           : '1800',
            's'            : '1',
            'vsnf'         : '1',
            'vsnval'       : '',
            'door'         : '',
            'appkey'       : 'kxR5R',
            'su'           : su,
            'service'      : 'miniblog',
            'servertime'   : servertime,
            'nonce'        : nonce,
            'pwencode'     : 'rsa2',
            'rsakv'        : rsakv,
            'sp'           : sp,
            'sr'           : '1680*1050',
            'encoding'     : 'UTF-8',
            'cdult'        : '2',
            'domain'       : 'weibo.com',
            'prelt'        : '0',
            'returntype'   : 'TEXT',
        })
        headers = {
                   #"Request": "POST /sso/login.php?client=ssologin.js(v1.4.15)&_=1400652171542 HTTP/1.1",
                   #"Accept": "*/*", 
                   "Content-Type": "application/x-www-form-urlencoded",
                   #"Referer": self.CALLBACK_URL,
                   #"Accept-Language": "zh-CN",
                   #"Origin": "https://api.weibo.com",
                   #"Accept-Encoding": "gzip, deflate",
                   #"User-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; EIE10;ZHCNMSE; rv:11.0) like Gecko",
                   #"Host": "login.sina.com.cn",
                   #"Connection": "Keep-Alive",
                   #"Cache-Control": "no-cache",
                   }
        url = "https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)"
        req = urllib2.Request(url, fields, headers)
        f = urllib2.urlopen(req)
        data = json.loads(f.read())
        return data["ticket"]
    
    def get_code_Security(self): 
        ticket = self.get_ticket()
        fields = urllib.urlencode({
            'action': 'submit', # must
            'display': 'default',
            'withOfficalFlag': '0', # must
            'quick_auth': 'null',
            'withOfficalAccount': '',
            'scope': '',
            'ticket': ticket, # must
            'isLoginSina': '',  
            'response_type': 'code', # must
            'regCallback': 'https://api.weibo.com/2/oauth2/authorize?client_id='+self.APP_KEY+'\
&response_type=code&display=default&redirect_uri='+self.REDIRECT_URL+'&from=&with_cookie=',
            'redirect_uri': self.REDIRECT_URL, # must
            'client_id': self.APP_KEY, # must
            'appkey62': 'kxR5R',
            'state': '', # must
            'verifyToken': 'null',
            'from': '', # must
            'userId': "", # do not need enter userId
            'passwd': "", # do not need enter password
            })
        LOGIN_URL = 'https://api.weibo.com/oauth2/authorize' 
        headers = {"User-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; EIE10;ZHCNMSE; rv:11.0) like Gecko",
                   "Referer": self.CALLBACK_URL,
                   "Content-Type": "application/x-www-form-urlencoded",
                   }
        req = urllib2.Request(LOGIN_URL, fields, headers)
        req_ =urllib2.urlopen(req)
        return_redirect_uri = req_.geturl()
        code = re.findall(r"(?<=code%3D).{32}|(?<=code=).{32}", return_redirect_uri) # url is formatted with %3D or= 
        return code 
    
    def get_code_NS(self):
        fields = urllib.urlencode({
            'action': 'submit', # must
            'display': 'default',
            'withOfficalFlag': '0', # must
            'quick_auth': 'null',
            'withOfficalAccount': '',
            'scope': '',
            'ticket': '', # must
            'isLoginSina': '',  
            'response_type': 'code', # must
            'regCallback': '',
            'redirect_uri': self.REDIRECT_URL, # must
            'client_id': self.APP_KEY, # must
            'appkey62': 'kxR5R',
            'state': '', # must
            'verifyToken': 'null',
            'from': '', # must
            'userId': self.USER_ID, # must
            'passwd': self.USER_PSWD, # must
            })
        LOGIN_URL = 'https://api.weibo.com/oauth2/authorize' 
        headers = {"User-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; EIE10;ZHCNMSE; rv:11.0) like Gecko",
                   "Referer": self.CALLBACK_URL,
                   "Content-Type": "application/x-www-form-urlencoded",
                   }
        r = urllib2.Request(LOGIN_URL, fields, headers)
        opener = get_opener(False) 
        urllib2.install_opener(opener)
        try:  
            f = opener.open(r)  
            return_redirect_uri = f.url   
            print "NS1", return_redirect_uri             
        except urllib2.HTTPError, e:  
            return_redirect_uri = e.geturl()  
            print "NS2", return_redirect_uri  
        # get the code
        #code = return_redirect_uri.split('=')[1]
        # re-generate with regexp expression
        code = re.findall(r"(?<=code%3D).{32}|(?<=code=).{32}", return_redirect_uri) 
        print code
        return code 

def sinaWeiboLogin(): 

    # sina weibo basic secret information
    APP_KEY = u'' # app key
    APP_SECRET = u'' # app secret
    REDIRECT_URL = ''
    USER_NAME = ''
    USER_PASSWD = ''
    
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=REDIRECT_URL)
    CALLBACK_URL = client.get_authorize_url()
    API = SinaAPI(CALLBACK_URL, APP_KEY, REDIRECT_URL, USER_NAME, USER_PASSWD)
    code = API.get_code_Security()
    requests = client.request_access_token(code)  
    access_token = requests.access_token # token return from sina  
    expires_in = requests.expires_in  
    
    # access_token  
    client.set_access_token(access_token, expires_in) 
    return client


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值