Backend Development 12 min read

Python Script for QQ Music QR Code Login: Session Retrieval and Cookie Handling

This tutorial demonstrates how to programmatically obtain a QQ Music QR‑code login session using Python by fetching the QR image, extracting and decrypting the required cookies, handling dynamic parameters, and completing the login flow with detailed code examples and explanations.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Script for QQ Music QR Code Login: Session Retrieval and Cookie Handling

The goal is to automate QQ Music's QR‑code login locally: display the QR image, wait for the user to scan it, then retrieve and preserve the login session.

Preparation : Define functions to show, delete, and save images across different operating systems.

import sys, os, subprocess

def showImage(img_path):
    try:
        if sys.platform.find('darwin') >= 0:
            subprocess.call(['open', img_path])
        elif sys.platform.find('linux') >= 0:
            subprocess.call(['xdg-open', img_path])
        else:
            os.startfile(img_path)
    except Exception:
        from PIL import Image
        img = Image.open(img_path)
        img.show()
        img.close()

def removeImage(img_path):
    if sys.platform.find('darwin') >= 0:
        os.system("osascript -e 'quit app \"Preview\"'")
    os.remove(img_path)

def saveImage(img, img_path):
    if os.path.isfile(img_path):
        os.remove(img_path)
    with open(img_path, 'wb') as fp:
        fp.write(img)

Fetching the QR code : Use the QQ Music QR‑login endpoint with fixed parameters and a random t value.

params = {
    'appid': '716027609',
    'e': '2',
    'l': 'M',
    's': '3',
    'd': '72',
    'v': '4',
    't': str(random.random()),
    'daid': '383',
    'pt_3rd_aid': '100497308'
}
response = session.get('https://ssl.ptlogin2.qq.com/ptqrshow?', params=params)
saveImage(response.content, os.path.join(os.getcwd(), 'qrcode.jpg'))
showImage(os.path.join(os.getcwd(), 'qrcode.jpg'))

After the QR image is displayed, the script extracts the qrsig cookie and converts it to ptqrtoken using the hash33 algorithm.

def __decryptQrsig(self, qrsig):
    e = 0
    for c in qrsig:
        e += (e << 5) + ord(c)
    return 2147483647 & e

Login verification loop : Repeatedly poll the QR‑login URL with the generated token and other dynamic parameters (including a timestamp‑based action value) until the server indicates a successful scan.

while True:
    params = {
        'u1': 'https://graph.qq.com/oauth2.0/login_jump',
        'ptqrtoken': ptqrtoken,
        'ptredirect': '0',
        'h': '1',
        't': '1',
        'g': '1',
        'from_ui': '1',
        'ptlang': '2052',
        'action': '0-0-%s' % int(time.time()*1000),
        'js_ver': '20102616',
        'js_type': '1',
        'login_sig': pt_login_sig,
        'pt_uistyle': '40',
        'aid': '716027609',
        'daid': '383',
        'pt_3rd_aid': '100497308',
        'has_onekey': '1'
    }
    resp = self.session.get(self.ptqrlogin_url, params=params)
    if '二维码未失效' in resp.text or '二维码认证中' in resp.text:
        pass
    elif '二维码已经失效' in resp.text:
        raise RuntimeError('Fail to login, qrcode has expired')
    else:
        break
    time.sleep(0.5)

Once the login succeeds, the script extracts the QQ number and follows the redirect to finalize the session.

qq_number = re.findall(r'&amp;uin=(.+?)&amp;service', resp.text)[0]
url_refresh = re.findall(r"'(https:.*?)'", resp.text)[0]
self.session.get(url_refresh, allow_redirects=False, verify=False)
print('账号「%s」登陆成功' % qq_number)

The complete class qqmusicScanqr encapsulates all these steps, providing a login() method that returns an authenticated requests.Session ready for further QQ Music API calls.

class qqmusicScanqr():
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)
        self.cur_path = os.getcwd()
        self.session = requests.Session()
        self.__initialize()
    # ... (methods shown above) ...

qq_login = qqmusicScanqr()
session = qq_login.login()
PythonautomationWeb ScrapingRequestsQR Loginsession
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.