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

  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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值