H5 获取用户openID,并把它传给后台


思路:openID是在公众号里识别用户的唯一标识

通过用户关注公众号(用户关注公众号有两种授权,一种是静默授权,一种是非静默授权,此时用的是静默授权),获取用户openID,并且把它传给后端。

 
 
import {getUrlParam} from './getUrlParam.js'
 
getCode () {
  if (sessionStorage.getItem("openid")&&sessionStorage.getItem("openid")!="undefined") {
    return false
  }
  var code = getUrlParam('code') // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openId
  var local = window.location.href
  var APPID = 'xxxxxxxxxx'
  if (code == null || code === '') {
    window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base&state=1_128b1ff67fdf4192836b1b0f05472f77#wechat_redirect'
  } else {
    this.getOpenId(code) //把code传给后台获取用户信息
  }
},
getOpenId (code) {  //把code传给后台,得到openid
  console.log(code)
},

getUrlParam.js:

export function getUrlParam (name) {
  //获取地址栏的参数
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
  var r = window.location.hash.substr(1).match(reg)
  console.log(location.hash)
  if (r != null) return unescape(r[2])
  return null
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM