关于CSDN微信登录接口的研究

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chouzhou9701/article/details/89149007

代码

import requests
import re
from threading import Thread
import time
import requests
from io import BytesIO
import http.cookiejar as cookielib
from PIL import Image
import sys
import psutil

requests.packages.urllib3.disable_warnings()


class show_code(Thread):
    def __init__(self,url):
        Thread.__init__(self)
        self.url = url

    def run(self):
        response = requests.get(self.url)
        img = Image.open(BytesIO(response.content))  # 打开图片,返回PIL image对象
        img.show()

def login():
    session = requests.session()
    session.cookies = cookielib.LWPCookieJar(filename='/home/wshuo/.cookie/csdn.txt') #这个写入cookie保存的路径
    response = session.get('https://open.weixin.qq.com/connect/qrconnect?appid=wx0ae11b6a28b4b9fc&scope=snsapi_login&redirect_uri=https%3A%2F%2Fpassport.csdn.net%2Fv1%2Fregister%2FpcAuthCallBack%3FpcAuthType%3Dweixin&state=csdn&login_type=jssdk&self_redirect=default&style=white&href=https://csdnimg.cn/release/passport/history/css/replace-wx-style.css',verify=False)
    uuid = re.findall('<img class="qrcode lightBorder" src="(.*?)" />',response.text)[0]
    img_url = 'https://open.weixin.qq.com' + uuid
    t= show_code(img_url)
    t.start()
    uuid = uuid.split('/')[-1]
    url = 'https://long.open.weixin.qq.com/connect/l/qrconnect?uuid='+uuid
    while 1:
        print(url)
        response = session.get(url,verify=False)
        code = re.findall("window.wx_code='(.*?)'",response.text)
        print(code)
        if code != ['']:
            for proc in psutil.process_iter():  # 遍历当前process
                if proc.name() == "display":  # 如果process的name是display
                    proc.kill()  # 关闭该process
            break
        time.sleep(1)


    url = 'https://passport.csdn.net/v1/register/pcAuthCallBack?pcAuthType=weixin&code=%s&state=csdn' % code[0]
    print(url)
    session.get(url)
    session.cookies.save()
    print('登录成功!')


if __name__ == '__main__':
    login()

大致逻辑就是csdn 在微信那边申请了一个接口(应该是参数appid),用于微信登录的,我们访问这个url,获取到其中的二维码地址,然后加载出来, 然后程序开始一直像一个url 发送请求(其实是用户扫描完二维码才会有响应),直到响应中有一部分字符串(应该是js的代码,返回字符串说明用户微信扫描已经确认登录了),然后把这个字符串当做参数去请求 csdn 的一个登录接口,返回响应的时候就会设置 cookie

其他

这个不仅仅是是 csdn 微信登录接口的逻辑, 也是 所有所有网站微信扫码登录的逻辑, 只要找到 网站在 微信那边登录的url,还有 最终请求的一个登录接口,直接替换上面的俩段url 就可以了,另外需要注意的是,有些网站最后的登录接口需要一个请求头,我登录简书的时候遇到这个问题,在请求头里面添加个 user-agent 就解决了。

猜你喜欢

转载自blog.csdn.net/chouzhou9701/article/details/89149007