• 【微信公众号】一、获取 access_token


    一、获取 access_token

    • 开发环境:Python

    说明:

    1. 微信公众号的 token,可以通过appid和appsecret登录后获取;
    2. token的有效期为两个小时;
    3. 如果本地开发,需要将本机的外网IP设为白名单,如果有服务器直接配置即可。

    原理:

    1. 定义一个配置文件,用来保存用户名密码tokentoken获取时间
    2. 读取配置文件,如果token获取时间存在,则根据时间差是否超过两个小时,直接获取或者重新获取。

    配置文件 conf.toml如下:

    [basic]
    app_id = "xxx"
    app_secret = "xxx"
    access_token = "xxx"
    token_time = 1700225491.118164
    
    [web]
    user_agents = [ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)", "Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.4.3.4000 Chrome/30.0.1599.101 Safari/537.36", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.59",]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    相关逻辑的python代码如下

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Author  : deepboat
    # @Desc    : 连接网络 获取 access_token
    # @Date    : 2023/11/17 17:41
    import json
    import random
    
    import requests
    import time
    import toml
    
    
    class Basic:
        def __init__(self, conf_file):
            self.confFile = conf_file
            self.confInfo = self.read_toml()
            self.appID = self.confInfo["basic"]["app_id"]
            self.appSecret = self.confInfo["basic"]["app_secret"]
            self.accessToken = self.confInfo["basic"]["access_token"]
            self.tokenTime = self.confInfo["basic"]["token_time"]
            self.userAgent = self.get_user_agent()
    
        def read_toml(self):
            conf_file = toml.load(self.confFile)
            return conf_file
    
        def write_toml(self):
            self.confInfo["basic"]["app_id"] = self.appID
            self.confInfo["basic"]["app_secret"] = self.appSecret
            self.confInfo["basic"]["access_token"] = self.accessToken
            self.confInfo["basic"]["token_time"] = self.tokenTime
            with open(self.confFile, "w", encoding="utf-8") as f:
                toml.dump(self.confInfo, f)
    
        # // 获取token
        def get_wechat_token(self):
            # 判断token是否过期
            if self.which_token_over():
    
                try:
                    params = {
                        "grant_type": "client_credential",
                        "appid": self.appID,
                        "secret": self.appSecret
                    }
                    headers = {'User-Agent': self.userAgent}
                    post_url = "https://api.weixin.qq.com/cgi-bin/token"
                    response_post = requests.post(url=post_url, params=params, headers=headers)
                    print(response_post)
                    print(response_post.text)
                    res = json.loads(response_post.text)
                    access_token = res["access_token"]
    
                    self.accessToken = access_token
                    self.tokenTime = time.time()
                    self.write_toml()
                    return self.accessToken
                except Exception as e:
                    print(e)
                    return False
            else:
                return self.accessToken
    
        # 判断token是否过期
        def which_token_over(self):
            # 获取当前时间戳 -- 时间戳是自1970年1月1日午夜以来的秒数
            now_time = time.time()
            # 用当前时间戳减去getTokenTime,大于两个小时就判定失效
            hour2 = 2 * 60 * 60
            if now_time - self.tokenTime > hour2:
                return True
            return False
    
        def get_user_agent(self):
            user_agent = random.choice(self.confInfo["web"]["user_agents"])
            return user_agent
    
    
    # if __name__ == '__main__':
    #     my_basic = Basic("../../docs/conf.toml")
    #     my_basic.get_wechat_token()
    
    
    • 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
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
  • 相关阅读:
    vitepress启动报错: getaddrinfo ENOTFOUND localhost
    兆骑科创创投平台,创赛承办,投融资对接,项目落地孵化
    终端仿真软件连接交换机调试步骤
    Scala--- Actor通信模型
    MySQL/Oracle字符串分割
    Vue-2.4sync修饰符
    PL/SQL变量,常量和数据类型(二)
    [从零开始学习FPGA编程-54]:高阶篇 - 基于IP核的FPGA开发-PLL锁相环IP核的原理与配置(Altera)
    mysql8.0.31 源码阅读
    新库上线 | CnOpenData中国星级酒店数据
  • 原文地址:https://blog.csdn.net/NQBXHN/article/details/134482568