python flask框架 微信公众号获取用户openid

微信官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

用户同意授权,获取code;通过code,去拿openid

直接上代码:

import requests
from urllib.parse import quote
from flask import jsonify, redirect

@mytest.route('/get_openid')
def get_openid():
    # 你的appid
    app_id = 'wx8888888888888888'
    # 你的回调路径
    back_url = quote('https://xxxx.xxxx.xxxx/mytest/openid_callback')
    url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + app_id + '&redirect_uri=' + back_url + \
          '&response_type=code&scope=snsapi_base#wechat_redirect'
    return redirect(url)

@mytest.route('/openid_callback', methods=['GET', 'POST'])
def openid_callback():
    data = request.args
    code = data['code'] if 'code' in data else None
    if not code:
        return jsonify({'code': -1, 'msg': 'no code'})
        
    # 你的appid
    app_id = 'wx8888888888888888'
    # 你的appsecret
    app_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    
    url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + app_id + '&secret=' + app_key + '&code=' + code + '&grant_type=authorization_code'
    r = requests.get(url)
    res = json.loads(r.text)
    open_id = res["openid"]
    return jsonify({'code': 200, 'open_id':open_id})

调用get_openid接口即可。

发布了3 篇原创文章 · 获赞 3 · 访问量 1392

猜你喜欢

转载自blog.csdn.net/DaLianMao_W/article/details/98039568