当前位置:网站首页>The applet is embedded in the web page, jumps to the applet and transmits parameters. The wechat applet realizes the authorization of official account to obtain openid
The applet is embedded in the web page, jumps to the applet and transmits parameters. The wechat applet realizes the authorization of official account to obtain openid
2022-07-19 01:33:00 【Pengzai studio】
Hello everyone , I'm Xiaobian pengzai , For school in the near future uniapp Developed a small campus program , The applet has some activities 、 consulting 、 Notice 、 Leave and other notices , You need to push the prompt through wechat , There are some restrictions on the subscription method of using applets , So the demand side wants to use the bound school official account to push , Because the applet gets the user's openId The official account. openId atypism , Therefore, we must call the official account authorization , Because the project has been basically completed , I feel very troublesome to add this suddenly , At first, I refused to modify it if I wanted to be lazy ...emo..., Later, I compromised , Or break through , Research and development !!!
After the blog domain name was sold last time , I haven't updated the article for a long time , Changed domain name , Many friends don't know the new website ( new www.sharedbk.com), Just sort it out and share it !

( Because of the development tool side , Let's preview the picture above ! That is, the access applet will first determine whether it is authorized through the official account openId, No jump to H5 Page for authorization , If you have one, just store it .)
First , We build a new one html file , Introduce wechat related js file
<!-- Be sure to pay attention to ,H5 Need to introduce wechat related js -->
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>next , We write custom js Some methods , The notes in it are relatively clear , How to jump to the applet , How to test the judgment logic , Simple and clear
<script>
const gzhId = '123456789'; // official account appid
const url = 'http://sharedbk.com/getOpenId.html'; // Authorization callback link
init(); // initialization
// Initialize validation
function init(){
if (!getUrlKey("code") && !sessionStorage.openId) {
// without code and openId, Let's jump to wechat authorization
window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + gzhId + "&redirect_uri=" + url +"&response_type=code&scope=snsapi_userinfo";
} else if (!sessionStorage.openId) {
// On the contrary, there are code, No, openId Call the background interface to get openId
getOpenId();
} else if (sessionStorage.openId) {
// If there is openId, Then jump directly to the applet
jumpBtn(sessionStorage.openId);
}
}
// Request background interface , obtain openId
function getOpenId(){
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({"code": getUrlKey("code")});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("http://sharedbk.com/getOpen", requestOptions)
.then(response => response.text())
.then(result => {
let res = JSON.parse(result);
if(res.code == '200'){
console.log(' Authorized success ');
sessionStorage.setItem("openId", res.data.openId); // Storage openId
jumpBtn(res.data.openId); // Jump to wechat applet
} else {
console.log(' privilege grant failed ');
window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + gzhId + "&redirect_uri=" + url +"&response_type=code&scope=snsapi_userinfo";
}
})
.catch(error => console.log('error', error));
}
// Jump to applet
function jumpBtn(val){
alert(val)
// val For transmission openId, Applet path self configuration
wx.miniProgram.navigateTo({
url:`/views/login?gzhOpenId=` + val,
success: (res) => {
console.log(res); // Page Jump success callback function
},
fail: (err) => {
console.log(err); // Callback function for page Jump failure
}
})
}
// To obtain parameters (http://www.sharedbk.com/post/188.html)
function getUrlKey (name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
}
</script>take html file save , Upload to server , So you can get the page link , Remember to be on it js Modify your own links , Then it needs to be in the background of the applet ( Development management => Development and setup => Business domain name ), Configure the domain name bound by the server into the business domain name , So you can call web-view Components .

Finish the above work , Let's continue with the following work in the applet ( I am a uniapp, Made a wechat judgment ,setStorageData and getStorageSyncData I encapsulated a local access method , You can directly use the storage method of wechat applet ), That is, when accessing applets , First determine whether the access has parameters , If you bring it, store it directly , Use without parameters web-view Jump to the web page for authorization ( Write your own small program web-view Page implementation is ok ).
onLoad: function(val) {
// #ifdef MP
if(val.gzhOpenId){ // Get the parameters passed
setStorageData('gzhOpenId', val.gzhOpenId); // Store official account openId
}
// Judge whether there is a official account openId, Use if it doesn't exist web-view Visit the authorization link to get
if(!getStorageSyncData('gzhOpenId')){
uni.navigateTo({
url: '/views/webViewPage/index?url=http://sharedbk.com/getOpenId.html'
});
}
// #endif
}
边栏推荐
- Uni app wechat applet - Mall (8) - order details
- js替换字符串某个字符,js修改字符串中指定字符
- MoveIt2——4.机器人模型和机器人状态
- JS get the suffix format of a file name
- E-commerce background management login
- Node的数据库编程(MySQL),增删改查
- Record buuctf [netding Cup 2018] unfinish1 problem solving ideas
- (八)Shell函数
- JS intercepts the first few digits of the string or the last few digits of the string
- uni-app微信公众号(4)——地址管理页面
猜你喜欢

mock平台的使用说明

小程序嵌入网页向小程序跳转并传参,微信小程序中实现公众号授权获取openId

网站如何统计访问人数?51LA如何安装使用?
![Stack injection [strong net cup 2019] random note](/img/94/9069ed79e994e3c2e96c3cd1f816ee.png)
Stack injection [strong net cup 2019] random note

Uni app wechat official account (4) - address management page

微信推送-模版消息参数配置

jsx 编译

Initial flask
![[SWPU 2019] network TTL encryption and some related knowledge](/img/c7/8a4b6e7808be9189e76563848b359d.png)
[SWPU 2019] network TTL encryption and some related knowledge

MoveIt2——2.MoveIt在RViz中的快速入门
随机推荐
About foreign key references, cross domain headers, and ref usage
Array Operations - judgment, de duplication, consolidation, expansion
今天的码农女孩学习了关于事件操作和ref属性的笔记并做了表单双向绑定的练习
智能指针(shared_ptr、unique_ptr、weak_ptr)
2022年暑假ACM热身练习2(总结)
(6) Test command
uni-app微信公众号(1)——网页授权登录
markdown编辑器语法——文字颜色、大小、字体与背景色的设置(转载)
Summary of XML external entity injection (xxE target recurrence)
(六)test命令
“我的”Bug大全(转载)
解决小程序自定义底部菜单切换闪动
From catf1ag two-hour AK match pwn/attack killing, summarize the common command guide of emergency response
JS get the suffix format of a file name
(10)文件包含
今天的码农女孩做了关于生命周期的笔记以及动态时钟的练习
object-fit:cover;在小程序中不起作用,小程序图片变形了如何处理
小程序嵌入网页向小程序跳转并传参,微信小程序中实现公众号授权获取openId
JS replaces a character in the string, and JS modifies the specified character in the string
[SWPU 2019] network TTL encryption and some related knowledge