当前位置: 首页 > 工具软件 > Python OpenID > 使用案例 >

python 用户关注公众号,获取openID,unionID

司寇旺
2023-12-01
  1. 微信官方文档——unionID
  2. 用户在关注公众号的前提下,再次进入到小程序,获取code,根据code,appid,secret获取用户的openID,unionID等信息。
  3. 代码示例:
    微信小程序——前端JS
var url = 'http://127.0.0.1:8000/'

  onLoad: function () {
    var that = this
    wx.login({
      success: res => {
        var code = res.code
        // 获取用户的openID 判断是否是新用户
        wx.request({
          url: url + 'get_unionid/',
          method: 'POST',
          data: {
            code: code
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            console.log('首页onLoad方法')
            console.log(res)
          }
        })
      }
    })
  },

python 后端

appid = 'xxxxxxxxxx'
secret = 'xxxxxxxxxxxxxxxxxxxx'

###### 获取unionid
@csrf_exempt
def get_unionid(request):
    if request.method == "POST":
        data = request.body
        data = json.loads(data.decode("utf8"))
        code = data.get("code")
        get_openid__ = open_union_function(code, appid, secret) # 调用获取openid方法
        return HttpResponse(1)
    else:
        return HttpResponse(0)


# 获取用户的openID,unionID 
def open_union_function(code, appid, secret):
    url_openid = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code'
    r_openid = requests.get(url_openid)
    dic = r_openid.json()  ## 把获取到的参数转json格式
    # dic = r_openid.text  ## 展示获取到的参数
    unionid = dic['unionid']
    openid = dic['openid']
    return unionid, openid
 类似资料: