首先,当我们一进入h5项目的时候,就会调用onLunch这个函数,接着需要去走授权这个操作,即调用getinit这个函数
一、理解
**微信静默授权授权需要四个最基本的参数**
- 公众号的openId
- autocode(微信授权码)=>(5分钟过期,并且不可以重复使用)
- 渠道channel
- 授权方式snsapi_userinfo;
通过授权我们可以获取用户的头像昵称等用户的基本信息
二、如何获取四个最基本的参数
公众号的openId、渠道channel=>这两个参数我们通过商户号获取
autocode(微信授权码)=>通过微信重定向获取
三、商户号如何获取
我们通过地址栏进行获取 没有则可以设置一个默认的
获取通过微信重定向获取code代码
四、代码
function getInit(){
const prams=getPrams();//获取浏览器地址?后面的参数
const code=prams.code;//微信授权的code
const mchNo = prams.mchNo;//商户号
const isSQ= uni.getStorageSync('isSQ')||null;//静默授权成功是否成功
//是否具有商户号 如果没有则可以自定义一个
if (mchNo == null || mchNo == '') {
mchNo = '商户号';//商户号自己定义
}
//通过商务号 去调取后台接口 获取公众号的openid、渠道等信息
let res=api.getMchNo({mchNo:mchNo});//调用后台接口 获取微信公众号的openid,channel渠道
//判断是否有微信授权码code 如果没有则进行微信
if(code == null || code == ''|| code == undefiend) {
let url = `${window.location.protocol}//${window.location.host}${window.location.pathname}` + '?mchNo=' + mchNo
const redirectUri=encodeURIComponent(url)
window.location.href =`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${res.openAppId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&#wechat_redirect`
return;
}else {
//开启静默授权
const res2 = await api.getOpenId({
openAppId:res.openAppId,
authCode: authCode,
authType:"snsapi_userinfo",
channel:res.channel
}
//如果授权成功将获取到的信息
if (res2.code == 0) {
isSQ= true;//静默授权成功 主要是为了后面的自动登录作为判断条件的 其他的基本信息根据需求进行本地存储
uni.setStorageSync('isSQ',isSQ)
}else {
let url = `${window.location.protocol}//${window.location.host}${window.location.pathname}` + '?mchNo=' + mchNo
const redirectUri=encodeURIComponent(url)
window.location.href =`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${res.openAppId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&#wechat_redirect`
return;
}
//自动登录部分
if(isSQ){
api·autologin();//自动登录接口
}else{
//不做处理或者跳转到登录页根据需求处理
}
}
//获取地址后面的参数
function getPrams() {
const url=window.location.search
let item=Object.fromEntries(new URLSearchParams(url.replace('/','')))
return item
}