• python 微信公众号,微信小程序wechatpy的使用


    第一章 Python 微信公众号,小程序入门之wechatpy的使用



    前言

    随着人工智能的不断发展,微信开发也越来越重要,很多人都开启了学习微信相关服务,本文就介绍了微信公众号和小程序的基础内容。


    一、wechatpy是什么?

    中文官方文档

    wechatpy 是一个微信 (WeChat) 的第三方 Python SDK, 实现了微信公众号、企业微信和微信支付等 API。

    二、微信公众号

    1.安装wechatpy

    安装
    pip install wechatpy -i https://pypi.tuna.tsinghua.edu.cn/simple/
    
    • 1
    • 2

    接入微信公众平台开发,开发者需要按照如下步骤完成:

    1、填写服务器配置

    2、验证服务器地址的有效性

    3、依据接口文档实现业务逻辑

    2.微信公众号服务器配置

    第一步:填写服务器配置
    登录微信公众平台官网后,在公众平台官网的开发 - 基本设置页面,勾选协议成为开发者,点击“修改配置”按钮,填写服务器地址(URL)、Token和EncodingAESKey,其中 URL 是开发者用来接收微信消息和事件的接口URL。Token可由开发者可以任意填写,用作生成签名(该 Token 会和接口 URL 中包含的 Token 进行比对,从而验证安全性)。EncodingAESKey由开发者手动填写或随机生成,将用作消息体加解密密钥。

    同时,开发者可选择消息加解密方式:明文模式、兼容模式和安全模式。模式的选择与服务器配置在提交后都会立即生效,请开发者谨慎填写及选择。加解密方式的默认状态为明文模式,选择兼容模式和安全模式需要提前配置好相关加解密代码,详情请参考消息体签名及加解密部分的文档 。
    官方服务器配置文档
    直接使用wechatpy来校验signature
    wechatpy文档

    from wechatpy.utils import check_signature
    from wechatpy.exceptions import InvalidSignatureException
    
    token  = 你在公众号服务器配置上相同的
    def check_signature_tool(self, signature, timestamp, nonce):
         try:
             check_signature(token, signature, timestamp, nonce)
             return True
         except InvalidSignatureException:  # 处理异常情况或忽略
             return False
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    注意⚠️返回的echostr要是int类型

    3.wechatpy WeChatClient设置redies缓存去保存access_token

    access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。
    官方获取Access token
    代码如下(示例):

    class WeixinWechatpy():
        def __init__(self):
            self.appid = WECHAT_APPID
            self.secret = WECHAT_SECRET
            self.token = WECHAT_TOKEN
            self.prefix = 'wechatpy'
            self.access_token_cache_url = "redis://localhost:6379/2"
    
        def get_WeChatClient(self):
            """
            获取WeChatClient对象
            :return:WeChatClient对象
            """
            redis_client = Redis.from_url(self.access_token_cache_url)
            session_interface = RedisStorage(
                redis_client,
                prefix=self.prefix
            )
            return WeChatClient(
                self.appid,
                self.secret,
                session=session_interface
            )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    参考链接


    总结

    以上就是今天要讲的内容,本文仅仅简单介绍了wechatpy的使用,而wechatpy提供了大量能使我们快速便捷地处理微信公众号,微信小程序的函数和方法。

    8.26 新增临时素材

    官方链接

    实话有点🚮了,只有一个 curl的实例
    以下两个方式

    1.本地文件
    path:文件地址
    files = {'p_w_picpath': open(path, 'rb')}
    
    2。网络读取到的二进制流
    content:文件二进制流
    files = { 'media' : ('tmp.jpg', content, 'image/jpg')}
    
    requests.post(url, files=files, timeout=10)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    8.29 微信公众号客服发文本消息乱码

    requests.post(url, data=json.dumps(data,ensure_ascii=False).encode('utf-8'))
    
    • 1

    8.29 微信公众号客服发文本消息换行

    content = "你好 /n 谢谢" # 一定要双引号
    data = {
                "touser": OPENID,
                "msgtype": msgtype,
                "text": {
                 "content": content
                 }
            }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    9.7 微信开放标签

    官方文档
    html文件

    DOCTYPE html>
    <html>
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
        <title>Demotitle>
    head>
    
    <body>
    <div id="app">
        <wx-open-launch-weapp path="pages/index/index" id="launch-wxapp" username="xxx">
        wx-open-launch-weapp>
        <wx-open-launch-app id="launch-btn" appid="xxx" extinfo='{"PageType":1001}'>
            <script type="text/wxtag-template">
                <style>
                        .btn {
                            padding: 12px
                        }
    
                </style>
                <button class="btn">点击打开APP</button>
            script>
        wx-open-launch-app>
    div>
    body>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.1.min.js">script>
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js">script>
    <script>
        getAppList()
    
        function getAppList() {
            $.ajax({
                url: "xxxxxx",
                type: "GET",
    			contentType: "application/json",
                success: function (data) {
                    const result = JSON.parse(data);
                    wx.config({
                        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                        appId: result.data.appid, // 必填,公众号的唯一标识
                        timestamp: parseInt(result.data.timestamp), // 必填,生成签名的时间戳
                        nonceStr: result.data.noncestr, // 必填,生成签名的随机串
                        signature: result.data.sign, // 必填,签名
                        jsApiList: ['onMenuShareTimeline', 'chooseImage'], // 必填,需要使用的JS接口列表
                        openTagList: ['wx-open-launch-weapp', 'wx-open-launch-app'] // 可选,需要使用的开放标签列表,例如['wx-open-launch-app']
                    })
                    wx.ready(function (res) {
                       
                    });
                    wx.error(function (res) {
                        // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名
                    });
                }
    
            });
        }
    
    script>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

  • 相关阅读:
    Hystrix 如何在不引入 Archaius 的前提下实现动态配置更新
    四六级听力考试高频词汇分类记忆-日常生活类
    捕捉数组越界访问问题
    React中useEffect Hook使用纠错
    暖通锅炉远程监控解决方案
    如何隐藏Selenium特征实现自动化网页采集
    Vmware+UOS-server-1050e虚拟机安装(含软件链接)
    Json递归删除和修改节点
    Docker 的数据管理 端口映射 容器互联 镜像的创建
    如何用手机给自己拍摄的视频静音?
  • 原文地址:https://blog.csdn.net/weixin_41486438/article/details/126709978