微信公众平台-服务器获取access_token-Python3.x代码

# -*- coding:utf-8 -*-
"""
微信公众平台 access_token重服务器获取
"""

import re
from urllib import request
from urllib import parse
from urllib.request import urlopen


def get_wx_access_token(appid, secret):
    """

    :return:
    """
    url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential'
    data = {
        'appid': appid,
        'secret': secret
    }
    data = parse.urlencode(data).encode('utf-8')  # 提交类型不能为str,需要为byte类型
    request_instance = request.Request(url, data)
    response = urlopen(request_instance)
    result = response.read()
    # bytes转str
    if isinstance(result, bytes):
        result_str = result.decode()
    else:
        result_str = result
    # str转dict
    result_dict = eval(result_str)
    return result_dict
    # if result_dict.get('access_token', False):
    #     return 'success', 0, result_dict['access_token']
    # else:
    #     return 'error', result_dict['errcode'], result_dict['errmsg']
    
# 这里的{appid}, {secret}按照公众平台基础配置上的信息填写
print(get_wx_access_token({appid}, {secret}))

你可能感兴趣的:(微信)