def get_access_token(appid, appsecret):
url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if 'access_token' in data:
return data['access_token']
else:
raise Exception(f"Failed to get access token: {data}")
else:
raise Exception(f"HTTP request failed with status code {response.status_code}")

# 替換為你的 APPID 和 APPSECRET
appid = "your_appid"
appsecret = "your_appsecret"

access_token = get_access_token(appid, appsecret)
print(f"Access Token: {access_token}")

2.3 發(fā)送模板消息

def send_template_message(access_token, openid, template_id, data):
url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}"
payload = {
"touser": openid,
"template_id": template_id,
"data": data
}
response = requests.post(url, json=payload)
if response.status_code == 200:
result = response.json()
if result['errcode'] == 0:
print("Template message sent successfully")
else:
raise Exception(f"Failed to send template message: {result}")
else:
raise Exception(f"HTTP request failed with status code {response.status_code}")

# 替換為你的 OpenID 和模板 ID
openid = "user_openid"
template_id = "your_template_id"

# 模板數(shù)據(jù)
data = {
"first": {
"value": "您好,您有一條新消息",
"color": "#173177"
},
"keyword1": {
"value": "2023-10-01",
"color": "#173177"
},
"keyword2": {
"value": "訂單已發(fā)貨",
"color": "#173177"
},
"remark": {
"value": "請及時查收",
"color": "#173177"
}
}

send_template_message(access_token, openid, template_id, data)

2.4 完整代碼

import requests

def get_access_token(appid, appsecret):
url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if 'access_token' in data:
return data['access_token']
else:
raise Exception(f"Failed to get access token: {data}")
else:
raise Exception(f"HTTP request failed with status code {response.status_code}")

def send_template_message(access_token, openid, template_id, data):
url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}"
payload = {
"touser": openid,
"template_id": template_id,
"data": data
}
response = requests.post(url, json=payload)
if response.status_code == 200:
result = response.json()
if result['errcode'] == 0:
print("Template message sent successfully")
else:
raise Exception(f"Failed to send template message: {result}")
else:
raise Exception(f"HTTP request failed with status code {response.status_code}")

# 替換為你的 APPID 和 APPSECRET
appid = "your_appid"
appsecret = "your_appsecret"

# 獲取 Access Token
access_token = get_access_token(appid, appsecret)
print(f"Access Token: {access_token}")

# 替換為你的 OpenID 和模板 ID
openid = "user_openid"
template_id = "your_template_id"

# 模板數(shù)據(jù)
data = {
"first": {
"value": "您好,您有一條新消息",
"color": "#173177"
},
"keyword1": {
"value": "2023-10-01",
"color": "#173177"
},
"keyword2": {
"value": "訂單已發(fā)貨",
"color": "#173177"
},
"remark": {
"value": "請及時查收",
"color": "#173177"
}
}

# 發(fā)送模板消息
send_template_message(access_token, openid, template_id, data)

3. 微信 Open Api 最佳實踐

3.1 緩存 Access Token

由于 Access Token 的有效期只有 2 小時,頻繁獲取會增加服務(wù)器負(fù)擔(dān)。建議將 Access Token 緩存起來,并在過期前重新獲取。

3.2 錯誤處理

在調(diào)用微信 API 時,可能會遇到各種錯誤,如網(wǎng)絡(luò)問題、API 限流等。建議在代碼中加入錯誤處理機制,確保程序的健壯性。

3.3 模板消息設(shè)計

模板消息的內(nèi)容應(yīng)簡潔明了,避免過多冗余信息。同時,合理使用顏色和格式,提升用戶體驗。

3.4 安全性

確保 APPIDAPPSECRET 的安全性,避免泄露。建議將敏感信息存儲在環(huán)境變量或配置文件中,而不是直接寫在代碼里。

4. 總結(jié)

本文詳細(xì)介紹了如何使用微信 Open API 進(jìn)行消息推送,并提供了完整的 Python 代碼示例。通過本文的學(xué)習(xí),你應(yīng)該能夠掌握微信消息推送的基本流程,并能夠在實際項目中應(yīng)用這些知識。希望本文對你有所幫助,祝你在微信開發(fā)中取得成功!

5. 常見問題解答

5.1 如何獲取用戶的 OpenID?

用戶的 OpenID 是用戶在公眾號下的唯一標(biāo)識。你可以通過微信網(wǎng)頁授權(quán)或用戶關(guān)注公眾號時獲取用戶的 OpenID。

5.2 如何創(chuàng)建模板消息?

在微信公眾平臺后臺,你可以創(chuàng)建和管理模板消息。創(chuàng)建模板消息后,你會獲得一個模板 ID,用于在代碼中發(fā)送模板消息。

5.3 如何處理 API 限流?

微信 API 有調(diào)用頻率限制。如果遇到限流問題,建議優(yōu)化代碼邏輯,減少不必要的 API 調(diào)用,并使用緩存機制減少重復(fù)請求。

6. 結(jié)語

微信 Open API 提供了強大的功能,幫助開發(fā)者實現(xiàn)豐富的微信應(yīng)用。通過本文的學(xué)習(xí),你應(yīng)該能夠掌握微信消息推送的基本技能,并能夠在實際項目中應(yīng)用這些知識。希望本文對你有所幫助,祝你在微信開發(fā)中取得成功!

上一篇:

交叉熵的Numpy實現(xiàn):從理論到實踐

下一篇:

復(fù)雜場景二維碼檢測技術(shù):挑戰(zhàn)、關(guān)鍵技術(shù)與應(yīng)用

我們有何不同?

API服務(wù)商零注冊

多API并行試用

數(shù)據(jù)驅(qū)動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費