Home > Article > Web Front-end > uni-app introductory tutorial - third-party login and sharing
Recommended (free): uni-app development tutorial
Article Table of contents
Preface
This article mainly introduces two aspects of APP development The basic functions are third-party login and sharing: including general login configuration, third-party login methods for WeChat mini programs and APPs, and sharing to chat and Moments. There are different interfaces and implementation methods using uni-app.
1. General configuration
Because the applet and APP login interfaces are different, cross-end compatibility processing needs to be done on the front end, at the same time, small programs on WeChat and other platforms generally only support third-party login of the host program, and cannot include other common third-party login methods, such as Weibo, QQ, etc., so they need to be separated from the APP.
1. WeChat mini program configuration
WeChat mini program must be configuredappid
, you need to apply for a mini program developer and obtain the appid and related Secret key to support individual developers.
After obtaining the appid, edit manifest.json. You can choose to complete the WeChat applet configuration or fill in the source code view. The instructions are as follows:
"mp-weixin" : { "appid" : "appid"}
You can click https://developers.weixin.qq.com/ Miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html View WeChat official documentation.
When using the test AppID provided by HBuilder, an error may be reported, such as Cannot read property 'forceUpdate' of undefined
. At this time, you can use the WeChat public platform https://developers.weixin.qq. If you apply for the AppID and AppSecret information of the sandbox environment test number in com/community/welogin?redirect_url=/sandbox and use it for project testing, errors will no longer be output.
2. APP side configuration
The APP side supports multiple third-party login methods such as WeChat, QQ, Weibo, etc. You need to apply for the corresponding developer and obtain the corresponding appid.
After obtaining the corresponding appid, edit manifest.json, perform visual operations, select App module configuration, perform OAuth authentication configuration, and select the required login method, such as QQ, WeChat, etc., as follows:
After selecting the corresponding login method, you need to fill in the AppID and other information.
2. Third-party login to WeChat Mini Program
1. Determine whether to log in
Required before logging in to WeChat Mini Program To determine whether to log in, you can define it in App.vue at this time, because the variables and methods defined in App.vue are global variables and methods, which can be called in other pages, just use Just declare the global
keyword.
The general principle of login is:
Obtain the user ID and random code and other information from the local cache according to the key, and then request the server to verify whether the user exists.
Random code is established to improve the security of the data interface. In addition, Redis, MemCache, etc. can also be used to achieve security assurance.
First define the global method to determine whether to log in in App.vue, as follows:
<script> export default { onLaunch: function() { console.log('App Launch') }, onShow: function() { console.log('App Show') }, onHide: function() { console.log('App Hide') } } global.isLogin = function() { try{ var suid = uni.getStorageSync('suid'); var srand = uni.getStorageSync('srand'); }catch(e){ //TODO handle the exception } if(suid == '' || srand == ''){ return false; } else{ return [suid, srand]; } }</script><style> /*每个页面公共css */ .red{ color:#ff0000; }</style>
Then call the global method in index.vue, as follows:
<template> <view> Index... </view></template><script> export default { data() { return { } }, onLoad() { var res = global.isLogin(); if(!res){ uni.showModal({ title: '登录提醒', content: '请登录', success:function(){ uni.navigateTo({ url: '/pages/login' }) } }) } }, onShow() { }, onHide() { }, methods: { } }</script><style></style>
At the same time Create a new login.vue page in the pages directory, as follows:
<template> <view> login... </view></template><script> export default { data() { return { } }, onLoad() { }, onShow() { }, onHide() { }, methods: { } }</script><style></style>
and add it to pages.json, as follows:
{ "pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages { "path": "pages/index/index", "style": { "navigationBarTitleText": "Uni Index", "backgroundColor": "#F0AD4E", "navigationBarTextStyle":"black" } }, { "path": "pages/about/about", "style": { "navigationBarTitleText": "Uni About" } }, { "path": "pages/news", "style": { "navigationBarTitleText": "Uni News", "navigationBarBackgroundColor":"#DD524D" } }, { "path": "pages/login", "style": { "navigationBarTitleText": "Uni Login", "navigationBarBackgroundColor":"#00aaff" } } ], "globalStyle": { "navigationBarTextStyle": "white", "navigationBarTitleText": "hello uniapp", "navigationBarBackgroundColor": "#ff557f", "backgroundColor": "#fffae8" }, "tabBar": { "color":"#F0AD4E", "selectedColor":"#007AFF", "backgroundColor":"#FFFFFF", "list": [ { "pagePath":"pages/index/index", "iconPath":"static/imgs/index_0.png", "selectedIconPath":"static/imgs/index_1.png", "text": "首页" }, { "pagePath":"pages/about/about", "iconPath":"static/imgs/about_0.png", "selectedIconPath":"static/imgs/about_1.png", "text":"关于我们" } ] }, "condition": { //模式配置,仅开发期间生效 "current": 0, //当前激活的模式(list 的索引项) "list": [{ "name": "index", //模式名称 "path": "pages/index/index", //启动页面,必选 "query": "interval=4000&autoplay=false" //启动参数,在页面的onLoad函数里面得到。 }, { "name": "about", //模式名称 "path": "pages/about/about", //启动页面,必选 "query": "interval=4000&autoplay=false" //启动参数,在页面的onLoad函数里面得到。 } ] }}
Display:
Obviously, after obtaining the non-logged-in status, it jumps to the login page.
2. Login page development
Login needs to determine the platform and carry out cross-end development, so conditional compilation is required. login.vue is as follows :
<template> <view> <!-- #ifdef MP-WEIXIN --> <button type="primary" open-type="getUserInfo" @getuserinfo="getuserinfo" withCredentials="true">微信登录</button> <!-- #endif --> </view></template><script> export default { data() { return {} }, onLoad() {}, onShow() {}, onHide() {}, methods: { getuserinfo: function(res){ console.log(res) } } }</script><style></style>
Display:
You can see that after successful login, the user's relevant information will be returned;
After clearing the cache and recompiling, before The login status does not exist and needs to be logged in again.
After logging in, check the return value res which contains some unencrypted basic information. There is iv attribute under the detail attribute, which is the initial vector of the encryption algorithm and can be decrypted. Information can also be used as a criterion for determining whether to authorize login;
rawData, the original data string excluding sensitive information, is used to calculate the signature.
It does not contain information such as openid and session_key, which needs to be obtained further:
First obtain the code, which is the user login credentials, through uni.login(OBJECT)
;
Then carry the code and pass uni.request(OBJECT)
Get openid and session_key.
login.vue如下:
<template> <view> <!-- #ifdef MP-WEIXIN --> <button type="primary" open-type="getUserInfo" @getuserinfo="getuserinfo" withCredentials="true">微信登录</button> <!-- #endif --> </view></template><script> export default { data() { return {} }, onLoad() {}, onShow() {}, onHide() {}, methods: { getuserinfo: function(res1) { console.log(res1) if (!res1.detail.iv) { uni.showToast({ title: '您已取消授权,登录失败', icon: "none" }) return false; } uni.login({ provider: 'weixin', success: function(res2) { console.log(res2); uni.request({ url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wxd3d4ee5ed8017903&secret=83c0d5efdfca99fc0509ff0d8956b830&js_code='+res2.code+'&grant_type=authorization_code', success:function(res3){ // get the openid and seesion key console.log(res3) }, fail:function(res4){ console.log(re4) } }) }, fail:function(r){ console.log(r) } }); } } }</script><style></style>
显示:
显然,此时获取到了openid
和session key
。
此外还可以获取unionid
,其在满一定条件的情况下才会返回。
获取到了openid和session key后,可以解密iv。
通过微信官方提供的SDK进行解密,可以实现解密的接口,如下:
login.vue如下:
<template> <view> <!-- #ifdef MP-WEIXIN --> <button type="primary" open-type="getUserInfo" @getuserinfo="getuserinfo" withCredentials="true">微信登录</button> <!-- #endif --> </view></template><script> export default { data() { return {} }, onLoad() {}, onShow() {}, onHide() {}, methods: { getuserinfo: function(res1) { console.log(res1) if (!res1.detail.iv) { uni.showToast({ title: '您已取消授权,登录失败', icon: "none" }) return false; } uni.login({ provider: 'weixin', success: function(res2) { console.log(res2); uni.request({ url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wxd3d4ee5ed8017903&secret=83c0d5efdfca99fc0509ff0d8956b830&js_code='+res2.code+'&grant_type=authorization_code', success:function(res3){ // get the openid and seesion key console.log(res3) // decrypt uni.request({ method: 'POST', url: 'https://hoa.hcoder.net/xcxencode/', header: {'content-type':'application/x-www-form-urlencoded'}, data: { appid: 'wxd3d4ee5ed8017903', sessionKey: res3.data.session_key, iv: res1.detail.iv, encryptedData: res1.detail.encryptedData }, success:function(res4){ console.log(res4) } }) }, fail:function(res5){ console.log(re5) } }) }, fail:function(r){ console.log(r) } }); } } }</script><style></style>
小程序登录时,可以设置选择携带手机号。
从之前button组件的open-type
属性中可以发现,getPhoneNumber
属性可以获取用户手机号,可以从@getphonenumber
回调中获取到用户信息。
三、APP第三方登录
实现APP登录也是通过条件编译实现。
login.vue如下:
<template> <view> <!-- #ifdef MP-WEIXIN --> <button type="primary" open-type="getUserInfo" @getuserinfo="getuserinfo" withCredentials="true">微信登录</button> <!-- #endif --> <!-- #ifdef APP-PLUS --> <button type="primary" @click="appWxLoin" withCredentials="true">用微信登录</button> <!-- #endif --> <button style="margin-top:50px;">手机号码登录</button> </view></template><script> export default { data() { return {} }, onLoad() {}, onShow() {}, onHide() {}, methods: { // miniprogram getuserinfo: function(res1) { console.log(res1) if (!res1.detail.iv) { uni.showToast({ title: '您已取消授权,登录失败', icon: "none" }) return false; } uni.login({ provider: 'weixin', success: function(res2) { console.log(res2); uni.request({ url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wxd3d4ee5ed8017903&secret=83c0d5efdfca99fc0509ff0d8956b830&js_code=' + res2.code + '&grant_type=authorization_code', success: function(res3) { // get the openid and seesion key console.log(res3) // decrypt uni.request({ method: 'POST', url: 'https://hoa.hcoder.net/xcxencode/', header: { 'content-type': 'application/x-www-form-urlencoded' }, data: { appid: 'wxd3d4ee5ed8017903', sessionKey: res3.data.session_key, iv: res1.detail.iv, encryptedData: res1.detail.encryptedData }, success: function(res4) { console.log(res4) } }) }, fail: function(res5) { console.log(re5) } }) }, fail: function(r) { console.log(r) } }); }, appWxLoin: function(){ console.log('login...') } } }</script><style></style>
此时不需要open-type等属性,只需要进行事件绑定就可以。
显示:
手机端显示:
显然,此时实现了条件编译,在不同的设备显示不同的按钮;
同时手机端点击时,控制台也输出信息。
先实现登录,需要获取服务商,判断是否安装微信,如果已安装则申请登录验证,如下:
<template> <view> <!-- #ifdef MP-WEIXIN --> <button type="primary" open-type="getUserInfo" @getuserinfo="getuserinfo" withCredentials="true">微信登录</button> <!-- #endif --> <!-- #ifdef APP-PLUS --> <button type="primary" @click="appWxLogin" withCredentials="true">用微信登录</button> <!-- #endif --> <button style="margin-top:50px;">手机号码登录</button> </view></template><script> export default { data() { return {} }, onLoad() {}, onShow() {}, onHide() {}, methods: { // miniprogram getuserinfo: function(res1) { console.log(res1) if (!res1.detail.iv) { uni.showToast({ title: '您已取消授权,登录失败', icon: "none" }) return false; } uni.login({ provider: 'weixin', success: function(res2) { console.log(res2); uni.request({ url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wxd3d4ee5ed8017903&secret=83c0d5efdfca99fc0509ff0d8956b830&js_code=' + res2.code + '&grant_type=authorization_code', success: function(res3) { // get the openid and seesion key console.log(res3) // decrypt uni.request({ method: 'POST', url: 'https://hoa.hcoder.net/xcxencode/', header: { 'content-type': 'application/x-www-form-urlencoded' }, data: { appid: 'wxd3d4ee5ed8017903', sessionKey: res3.data.session_key, iv: res1.detail.iv, encryptedData: res1.detail.encryptedData }, success: function(res4) { console.log(res4) } }) }, fail: function(res5) { console.log(re5) } }) }, fail: function(r) { console.log(r) } }); }, appWxLogin: function() { console.log('login...'); uni.getProvider({ service: 'oauth', success: function(res) { console.log(res.provider) if (~res.provider.indexOf('weixin')) { uni.login({ provider: 'weixin', success: function(loginRes) { console.log(JSON.stringify(loginRes)); uni.getUserInfo({ provider: 'weixin', success: function(infoRes) { console.log(JSON.stringify(infoRes)); console.log('用户昵称为:' + infoRes.userInfo.nickName); } }); } }); } } }); } } }</script><style></style>
显示:
手机端显示:
显然,实现了在APP端调用微信登录;
登录后,输出了相应的信息。
四、分享接口
分享是一个很重要的功能。
1.小程序分享
小程序只支持分享到聊天界面(包括微信好友和微信群),不支持分享到朋友圈,是使用onShareAppMessage
生命周期实现的。
index.vue如下:
<template> <view> Index... </view></template><script> export default { data() { return { } }, onLoad() { var res = global.isLogin(); if(!res){ uni.showModal({ title: '登录提醒', content: '请登录', success:function(){ uni.navigateTo({ url: '/pages/login' }) } }) } }, onShow() { }, onHide() { }, onShareAppMessage:function(){ return { title: 'Share test...', path: 'pages/index/index' } }, methods: { } }</script><style></style>
显示:
可以看到,实现了分享功能。
2.APP分享
APP中要实现分享,需要在manifest.json中进行配置,如下:
先实现分享纯文字,index.vue如下:
<template> <view> <!-- #ifdef APP-PLUS --> <button type="primary" @click="share">点击分享</button> <!-- #endif --> </view></template><script> export default { data() { return { } }, onLoad() { }, onShow() { }, onHide() { }, onShareAppMessage:function(){ return { title: 'Share test...', path: 'pages/index/index' } }, methods: { share: function(){ uni.share({ provider: "weixin", scene: "WXSceneSession", type: 1, summary: "我正在参加CSDN年度博客之星活动,请点击链接 https://bss.csdn.net/m/topic/blog_star2020/detail?username=cufeecr 投一票吧,先在此谢过啦!!", success: function (res) { console.log("success:" + JSON.stringify(res)); }, fail: function (err) { console.log("fail:" + JSON.stringify(err)); } }); } } }</script><style></style>
显示:
手机端显示:
显然,控制台输出了分享成功的信息;
同时,APP成功调用了微信分享。
再实现分享图文,如下:
<template> <view> <!-- #ifdef APP-PLUS --> <button type="primary" @click="share">点击分享</button> <!-- #endif --> </view></template><script> export default { data() { return { } }, onLoad() { }, onShow() { }, onHide() { }, onShareAppMessage:function(){ return { title: 'Share test...', path: 'pages/index/index' } }, methods: { share: function(){ uni.share({ provider: "weixin", scene: "WXSceneSession", type: 0, href: "https://bss.csdn.net/m/topic/blog_star2020/detail?username=cufeecr", title: "cufeecr年度博客之星评选", summary: "我正在参加CSDN年度博客之星活动,请点击链接 https://bss.csdn.net/m/topic/blog_star2020/detail?username=cufeecr 投一票吧,先在此谢过啦!!", imageUrl: "https://img-blog.csdnimg.cn/20210112093810423.png", success: function (res) { console.log("success:" + JSON.stringify(res)); }, fail: function (err) { console.log("fail:" + JSON.stringify(err)); } }); } } }</script><style></style>
显示:
手机端显示:
显然,实现了分享图文到微信好友或微信群。
还可以分享到微信朋友圈,如下:
<template> <view> <!-- #ifdef APP-PLUS --> <button type="primary" @click="share">点击分享</button> <!-- #endif --> </view></template><script> export default { data() { return { } }, onLoad() { }, onShow() { }, onHide() { }, onShareAppMessage:function(){ return { title: 'Share test...', path: 'pages/index/index' } }, methods: { share: function(){ uni.share({ provider: "weixin", scene: "WXSenceTimeline", type: 2, imageUrl: "https://img-blog.csdnimg.cn/20210112093810423.png", success: function (res) { console.log("success:" + JSON.stringify(res)); }, fail: function (err) { console.log("fail:" + JSON.stringify(err)); } }); } } }</script><style></style>
显示:
手机端显示:
已经实现了分享消息到朋友圈。
总结
第三方登录和分享是APP和小程序的基本功能,对于APP和小程序有不同的实现方式,相比较而言,APP实现更简单,都是其他功能的基础和起步。
更多相关免费了解敬请关注uni_app教程栏目!
The above is the detailed content of uni-app introductory tutorial - third-party login and sharing. For more information, please follow other related articles on the PHP Chinese website!