current position:Home>Python code to scan code to pay attention to official account login
Python code to scan code to pay attention to official account login
2022-01-30 16:10:11 【Ice and wind all over the sky】
General train of thought : Call wechat QR code interface with parameters to generate QR code , The front end displays the QR code and carries out long link communication with the server at the same time , Monitor attention status , If there are concerns about the corresponding scene code parameters , Then log in .
The following is the service diagram
Main code implementation :
Get QR code part
1. take access_token
app_id = 'xxxx'
app_secret = 'xxxxxx'
url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}'.format(app_id, app_secret)
resp = requests.get(url)
rs = util.get_redis_con()
access_token = resp.json()['access_token']
print(access_token)
Copy code
This access_token The term of validity is two hours , So it is suggested to write a scheduled task , Execute every hour , Deposit in redis, Use it every time redis Take it .
2. take ticket
my_scene_str = 'xxxxx' # The scene code can be used as key Put it in redis And set an expiration time as QR code
url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={0}'.format(access_token)
data = {
"expire_seconds": 604800,
"action_name": "QR_STR_SCENE",
"action_info": {"scene": {"scene_str": md5_user_key}}
}
resp = requests.post(url, json=data)
ticket = resp.json()['ticket']
Copy code
3. Take QR code picture ( When the picture is returned here, the scene code is also returned to the front end , In this way, if the front end uses polling to obtain the attention status, it can not use long links )
url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + ticket
resp = requests.get(url)
img = base64.b64encode(resp.content).decode('ascii')
print(img)
Copy code
The pictures taken from this are base64 Back to the front end , Front end use src="data:image/png;base64,"+img You can show
Get the attention status value
Method 1 : Use scenario code polling
Send request polling md5_user_key
Method 2 : Use scene code to establish long link connection , Wait for the server to push
flask It is recommended to use socketio
Analyze wechat server message
New attention is paid to the content of user code scanning message
<xml> <ToUserName><![CDATA[xxxxxxxxxxxxx]]></ToUserName> <FromUserName><![CDATA[xxxxxxxxxxx]]></FromUserName> <CreateTime>1609128953</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[subscribe]]></Event> <EventKey><![CDATA[xxxxxx]]></EventKey> <Ticket><![CDATA[xxxxxxxx]]></Ticket> </xml> Copy code
Content of code scanning message of old users
<xml> <ToUserName><![CDATA[xxxxxxxxxxxx]]></ToUserName> <FromUserName><![CDATA[xxxxxxxxxxxxx]]></FromUserName> <CreateTime>1609127524</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[SCAN]]></Event> <EventKey><![CDATA[xxxxxxxxxxxxxx]]></EventKey> <Ticket><![CDATA[xxxxxxxxxxxxxxxxxxx]]></Ticket> </xml> Copy code
ToUserName: Members of the public, id
FromUserName: User openid
import xml.etree.ElementTree as ET
root = ET.fromstring(request.data.decode('utf-8'))
dic = {}
for x in root:
dic[x.tag] = x.text
if dic.get('MsgType') == 'event':
if dic.get('Event') == 'subscribe':
parse_subscribe(dic) # Scan the code for new users
if dic.get('Event') == 'SCAN':
parse_scan(dic) # We have paid attention to the user scanning code
Copy code
Use openid Get the concerned wechat user information
url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={access_token}&openid={open_id}&lang=zh_CN"
resp = requests.get(url.format(access_token=access_token, open_id=open_id))
resp.encoding = 'utf-8'
return resp.json()
Copy code
Returns the parameter {'subscribe': 1, 'openid': 'xxxxxxxxxxxxxxxxxxx', 'nickname': 'xxx', 'sex': 1, 'language': 'zh_CN', 'city': 'xx', 'province': 'xx', 'country': 'xx', 'headimgurl': 'http://thirdwx.qlogo.cn/mmopen/xxxxxxxxxxxxxxxxxx/xxx', 'subscribe_time': 1609128953, 'unionid': 'xxxxxxxxxxxxxxxxx', 'remark': '', 'groupid': 0, 'tagid_list': [], 'subscribe_scene': 'ADD_SCENE_QR_CODE', 'qr_scene': 0, 'qr_scene_str': 'xxxxxxxxxxxxxxxxxxxx'} Copy code
\
copyright notice
author[Ice and wind all over the sky],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301610086435.html
The sidebar is recommended
- Python notes (6): definition and use of lists
- Python notes (V): string operation
- Python notes (IV): use of functions and modules
- Python notes (3): conditional statements and circular statements
- Python notes (II): lexical structure
- Notes on python (I): getting to know Python
- [Python data structure series] - tree and binary tree - basic knowledge - knowledge point explanation + code implementation
- [Python daily homework] Day7: how to combine two dictionaries in an expression?
- How to implement a custom list or dictionary in Python
- 15 advanced Python tips for experienced programmers
guess what you like
-
Python string method tutorial - how to use the find() and replace() functions on Python strings
-
Python computer network basics
-
Python crawler series: crawling global airport information
-
Python crawler series: crawling global port information
-
How to calculate unique values using pandas groupby
-
Application of built-in distribution of Monte Carlo simulation SciPy with Python
-
Gradient lifting method and its implementation in Python
-
Pandas: how to group and calculate by index
-
Can you create an empty pandas data frame and fill it in?
-
Python basic exercises teaching! can't? (practice makes perfect)
Random recommended
- Exploratory data analysis (EDA) in Python using SQL and Seaborn (SNS).
- Turn audio into shareable video with Python and ffmpeg
- Using rbind in python (equivalent to R)
- Pandas: how to create an empty data frame with column names
- Talk about quantifying investment using Python
- Python, image restoration in opencv - CV2 inpaint
- Python notes (14): advanced technologies such as object-oriented programming
- Python notes (13): operations such as object-oriented programming
- Python notes (12): inheritance such as object-oriented programming
- Chapter 2: Fundamentals of python-5 Boolean
- Python notes (11): encapsulation such as object-oriented programming
- Python notes (10): concepts such as object-oriented programming
- Gradient lifting method and its implementation in Python
- Van * Python | simple crawling of a site course
- Chapter 1 preliminary knowledge of pandas (list derivation and conditional assignment, anonymous function and map method, zip object and enumerate method, NP basis)
- Nanny tutorial! Build VIM into an IDE (Python)
- Fourier transform of Python OpenCV image processing, lesson 52
- Introduction to python (III) network request and analysis
- China Merchants Bank credit card number recognition project (Part I), python OpenCV image processing journey, Part 53
- Introduction to python (IV) dynamic web page analysis and capture
- Python practice - capture 58 rental information and store it in MySQL database
- leetcode 119. Pascal's Triangle II(python)
- leetcode 31. Next Permutation(python)
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat [2]
- This is what you should do to quickly create a list in Python
- On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
- Python OpenCV image area contour mark, which can be used to frame various small notes
- How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
- Initial Python tuple
- Introduction to Python urllib module
- Advanced Python Basics: from functions to advanced magic methods
- Python Foundation: data structure summary
- Python Basics: from variables to exception handling
- Python notes (22): time module and calendar module