一、创建二维码ticket
You can use the requests library to perform the HTTP POST request. If you don’t have it installed, you can install it using pip:
pip install requests
Here’s the Python code to make the POST request with both JSON examples:
import requests
import json
url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN"
# Example 1: QR_SCENE
data1 = {
"expire_seconds": 604800,
"action_name": "QR_SCENE",
"action_info": {"scene": {"scene_id": 123}}
}
# Example 2: QR_STR_SCENE
data2 = {
"expire_seconds": 604800,
"action_name": "QR_STR_SCENE",
"action_info": {"scene": {"scene_str": "test"}}
}
# Choose the data you want to use (data1 or data2)
data = data1
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=json.dumps(data), headers=headers)
if response.status_code == 200:
print("Request successful!")
print(response.json())
else:
print("Request failed. Status code:", response.status_code)
print(response.text)
Remember to replace TOKEN in the URL with your actual access token. This code uses the first JSON example (data1) by default. To use the second JSON example (data2), change the data variable assignment to data = data2.
二、通过ticket换取二维码
You can use the requests library to perform the HTTPS GET request and download the image. Here’s the Python code to make the request and save the image:
import requests
from urllib.parse import quote
ticket = "YOUR_TICKET"
encoded_ticket = quote(ticket)
url = f"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={encoded_ticket}"
response = requests.get(url)
if response.status_code == 200:
print("Request successful!")
with open("qrcode.jpg", "wb") as f:
f.write(response.content)
print("QR code saved as qrcode.jpg")
else:
print("Request failed. Status code:", response.status_code)
print(response.text)
Remember to replace YOUR_TICKET with your actual ticket. The code above will download the image and save it as “qrcode.jpg” in the current working directory. If the ticket is invalid or there’s an error, the code will print the HTTP error code and response text.