溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python如何實(shí)現(xiàn)微信小程序用戶登錄、模板推送

發(fā)布時(shí)間:2021-04-06 10:50:11 來(lái)源:億速云 閱讀:293 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹了python如何實(shí)現(xiàn)微信小程序用戶登錄、模板推送,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

Python 實(shí)現(xiàn)微信小程序的用戶登錄

小程序可以通過(guò)官方提供的登錄鄧麗來(lái)獲取用戶身份的標(biāo)示, 具體文檔可以參考 官方文檔, 通過(guò)流程時(shí)序可以看到, 對(duì)于需要和前端配合的服務(wù)端開發(fā), 主要實(shí)現(xiàn)的就是通過(guò)小程序提供的 code 換取用戶的 openid 和 session_key, 并用換取到的 openid 和 secret_key 作為自定義的登錄態(tài). 分析后得知, 作為小程序后端的開發(fā), 主要實(shí)現(xiàn)以下幾部分內(nèi)容:

  • 提供一個(gè) HTTP 接口, 供小程序方使用, 傳遞code;

  • 換取用戶身份標(biāo)識(shí);

  • 維護(hù)一個(gè)自定義的登錄態(tài);

  • 需要存儲(chǔ)用戶的 openid , 以備后續(xù)使用.

1.提供給小程序一個(gè) HTTP 接口, 接口而使用 Tornado 框架

簡(jiǎn)化闡述, 代碼沒(méi)有做異常處理

class LoginHandler(RequestHandler):
 def post(self):
 req_data = json.loads(self.request.body)
 js_code = req_data.get('js_code')
 
 # 開始換取用戶的信息
 user_info = get_user_info(js_code=js_code)
 openid = user_info['openid']
 session_key = user_info['session_key']
 user_uuid = str(uuid.uuid4()) # 暴露給小程序端的用戶標(biāo)示
 
 # 用來(lái)維護(hù)用戶的登錄態(tài)
 User.save_user_session(
   user_uuid=user_uuid,
   openid=openid,
   session_key=session_key
 )
 
 # 微信小程序不能設(shè)置cookie, 把用戶信心存在了headers中
 self.set_header('Authorization', user_uuid)
 # 存儲(chǔ)用戶信息
 User.save_user_info(open_id=openid)
 self.set_status(204)

2.換取用戶身份標(biāo)示, 直接使用 Requests包 請(qǐng)求微信的相關(guān)接口, 獲取數(shù)據(jù)

def get_user_info(js_code):

 req_params = {
 "appid": 'app_id', # 小程序ID
 "secret": 'secret', # 小程序 secret
 "js_code": js_code,
 "grant_type": 'authorization_code'
 } 
 req_resutl = requests.get('https://api.weixin.qq.com/sns/jscode2session', params=req_params, timeout=3, verify=False)
 return req_result.json()

3.維護(hù)一個(gè)自定義的登錄態(tài), 使用 Redis

user_redis = StrictRedis.from_url('redis//localhost:6379')

class User(object):
 REDIS_EXPIRES = 7 * 24 * 60 * 60
 
 @classmethod
 def save_user_session(cls, user_uuid, openid, session_key):
 user_session_value = {
 'openid':openid,
 'session_key':session_key
 }
 user_session_key = 'US:' + user_uuid
 with user_redis.pipeline(transaction=False) as pipe:
 pipe.hmset(user_session_key, user_session_value)
 pipe.expire(user_session_key, cls.REDIS_EXPIRES)
 pipe.execute()

4.存儲(chǔ)用戶信息, 以備后用, ORM使用 SQLAlchemy

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base

# mysql 相關(guān)設(shè)置
engine = create_engine('mysql://root:pwd@localhost/wechat')
conn = engine.connect()

Base = declarative_base()
Base.metadata.reflect(engine)
tables = Base.metadata.tables

class User(object):
 table = tables['user']

 @classmethod
 def save_user_info(cls, open_id):
 # 存儲(chǔ)用戶信心
 sql = cls.table.insert().values(open_id=open_id)
 conn.execute(sql)

SQL 語(yǔ)句

CREATE TABLE `user`(
 `id` int(20) unsigned NOT NULL AUTO_INCREMENT,
 `open_id` varchar(32) NOT NULL COMMENT '用戶 open_id',
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時(shí)間',
 `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時(shí)間',
 PRIMARY KEY (`id`),
 KEY `idx_oid` (`open_id`)
) ENGINE=InnoDB default CHARSET=utf8mb4;

Template: 通過(guò)代碼發(fā)送微信模板消息

import json

import requests
from redis import StrictRedis
from tornado.web import RequestHandler

redis = StrictRedis.from_url('redis//localhost:6379')

def get_access_token():
 payload = {
 'grant_type': 'client_credential',
 'appid': 'appid',
 'secret': 'secret'
 }
req = requests.get('https://api.weixin.qq.com/cgi-bin/token', params=payload, timeout=3, verify=False)
access_token = req.json().get('access_token')
redis.set('ACCESS_TOKEN', access_token)

class FormHandler(RequestHandler):
 def post(self):
 req_data = self.request.body
 req_data = json.loads(req_data)
 form_id = req_data.get('from_id')
 remplate_push(form_id) # 使用消息進(jìn)行模板推送
 
def template_push(form_id):
 data = {
 "touser": 'open_id',
 "template_id": 'template_id',
 "page": 'pages/index/index',
 "form_id": form_id,
 "data":{
 "keyword1":{
 "value": "value"
 }
 }
 "emphasis_keyword": ''
 }
 access_token = redis.get('ACCESS_TOKEN')
 push_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={}'.format(access_token)
 requests.post(push_url, json=data, timeout=3, verify=False)

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“python如何實(shí)現(xiàn)微信小程序用戶登錄、模板推送”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI