当前位置:网站首页>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
}
边栏推荐
- Colorful text advertising code, text advertising code beautification version, add text advertising tutorials to the website
- C Programming Language (2nd Edition)--读书笔记--1.5.4
- P6-day01-general attempt (P4 review)
- promise
- If the website is hacked, what if you jump to other websites through Baidu / Sogou and other search keywords?
- 自己封裝的風格化的開關卡片組件
- Replace special characters in URL (%e2%80%8b)
- 数据库连接池、sequelize实现增删改查等操作
- everything搜索不到startup_lpc11x.s文件
- JSX 语法
猜你喜欢

Registry hijacking triggers malicious programs

object-fit:cover; It doesn't work in the applet. How to deal with the deformation of the applet image

mock平台的使用说明

Use bat to automatically execute CMD commands (multiple commands or a single command)

Cve-2022-34265 Django extract & TRUNC SQL injection vulnerability recurrence
![[SWPU 2019] network TTL encryption and some related knowledge](/img/c7/8a4b6e7808be9189e76563848b359d.png)
[SWPU 2019] network TTL encryption and some related knowledge

Uni app wechat applet - Mall (4) - merchants

页面布局——三栏布局解决方式

Express中间件的分类及使用

js替换字符串某个字符,js修改字符串中指定字符
随机推荐
Single page application spa and multi page application MPa
js替换字符串某个字符,js修改字符串中指定字符
el-form特殊字符校验
列表懒加载和图片懒加载
Uniapp calls the map to query the location and mark the location
智能指针(shared_ptr、unique_ptr、weak_ptr)
jsx 编译
缤纷彩色文字广告代码,文字广告代码美化版,给网站添加文字广告教程
Uni app wechat applet - Mall (3) - Mall Homepage
The C Programing Language-2nd--笔记--4.11.3
Supplementary knowledge of attributes and methods of regular, JWT token, ronglianyun, celery, channel group, SKU, SPU, request object
自己封裝的風格化的開關卡片組件
The C Programing Language--(2nd)--笔记--4.11.2
object-fit:cover;在小程序中不起作用,小程序图片变形了如何处理
About foreign key references, cross domain headers, and ref usage
量化行业知识汇总
js截取字符串前几位或者截取字符串后几位
今天的码农女孩学习了关于nodejs和REPL 交互式解释器的知识
Uni app wechat applet - Mall (8) - order details
Vue project deployment, cleaning cache