首先确定您的小程序和公众号的认证是同一个主体!
1.前端代码,当前是小程序内嵌入 web-view 服务器的html页面
1.1 https://www.***.com/h5 这个地址为服务器上的html地址
<template>
<web-view src="https://www.****.com/h5"></web-view>
</template>
<script>
import { publicApi } from '@/api'
export default {
data() {
return {}
},
async onLoad(option) {
if (option && option.openid) {
let userInfo=uni.getStorageSync('userInfo');
if(userInfo && Object.keys(userInfo).length && option.openid){
let res=await publicApi().userOfficeUpdate({
"userNo": userInfo.userNo,
"officeId": option.openid
})
if(!res.hasErr){
uni.$u.toast('数据同步成功')
setTimeout(()=>{
uni.redirectTo({
url: '/pages/page/my/index'
})
},500)
}
}else{
uni.$u.toast('数据同步失败')
}
}
},
methods: {}
}
</script>
2 H5页面 放在服务器 通过域名 https://www.****.com/h5 可以直接访问
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>公众号信息网页授权</title>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script type="text/javascript">
let url = window.location.href;
let appId = '';//微信公众号appid
let code=getUrlParam('code');
function getUrlParam (name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
let url = window.location.href.split('#')[0]
let search = url.split('?')[1]
if (search) {
var r = search.substr(0).match(reg)
if (r !== null) return unescape(r[2])
return null
} else {
return null
}
}
if (url.includes('code') && code!=null && code!=undefined) {
console.log('ajax')
$.ajax({//URL当前地址是请求后端接口传入code值获取公众号信息
url:'',
data:JSON.stringify({ code: getUrlParam('code') }),
type: 'post',
dataType: 'json',
contentType:'application/json',
success: function(result) {
console.log(result)
if(!result.hasErr && result.data){
if (wx.miniProgram) {//回退到小程序web-view页面并带入参数回传
wx.miniProgram.reLaunch({
url: '/pages/page/webView/index?openid=' + result.data.openId,
success: function() {},
fall: function() {}
})
}
}
},
error: function(err) {
console.log(err)
}
})
} else {
// scope=snsapi_base为静默 不需要客户点确认授权
window.location.href=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
}
</script>
<style>
body,html{
background: #F4F4F3;
}
</style>
</head>
<body>
</body>
</html>
3.nginx服务器配置
#小程序中业务认证域名配置文件访问路径
location / {
alias /www/hiyfiles/h5/;
index index.html index;
try_files $uri $uri/ =404;
}
#访问公众号h5页面文件访问路径
location /h5 {
alias /www/hiyfiles/h5/;
index index.html index;
}