前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >uni-app入门教程(7)第三方登录和分享

uni-app入门教程(7)第三方登录和分享

作者头像
cutercorley
发布2021-01-14 10:59:33
1.6K2
发布2021-01-14 10:59:33
举报

文章目录

各位粉丝小伙伴、小哥哥小姐姐、路过的读者朋友,感谢您的浏览和支持。 有幸入围一年一度的CSDN博客之星评选活动,希望大家可以点击链接 https://bss.csdn.net/m/topic/blog_star2020/detail?username=cufeecr扫描下方二维码投出宝贵的一票或者多票,让我更进一步,江湖救急,要是有帮得上忙的地方绝对义不容辞,可以为你互投,也可以帮忙下载资源,还可以互关三连,多谢啦。 新的一年,愿我们一起变得更强???

前言

本文主要介绍了APP开发的两大基本功能,即第三方登录登录和分享:包括登录通用配置,微信小程序和APP的第三方登录方式,和分享到聊天和朋友圈,使用uni-app实现有不同的接口和实现方式。

一、通用配置

因为小程序和APP登录接口不同,需要在前端进行跨端兼容处理,同时微信等平台的小程序一般只支持所属宿主程序的第三方登录,而无法包括其他的常见第三方登录方式,如微博、QQ等,因此需要与APP分开。

1.微信小程序端配置

微信小程序端必须配置appid,需要申请小程序开发者并获取appid及相关秘钥,支持个人开发者。 获取appid后编辑manifest.json,可以选择微信小程序配置完成,也可以选择源码视图填充,示意如下:

"mp-weixin" : {
    "appid" : "appid"
}

可点击https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html查看微信官方文档。

在使用HBuilder提供的测试AppID可能会报错,例如Cannot read property 'forceUpdate' of undefined,此时可以在微信公众平台https://developers.weixin.qq.com/community/welogin?redirect_url=%2Fsandbox中申请沙箱环境测试号的AppID和AppSecret信息,并用于项目测试,就不会再输出错误。

2.APP端配置

APP端支持微信、QQ、微博等多种第三方登录方式,都需要申请对应的开发者并获取对应的appid。 获取对应的appid后,编辑manifest.json,进行可视化操作,选择App模块配置,进行OAuth鉴权配置,选择所需要的登录方式,如QQ、微信等,如下:

uniapp login app oauth permission
uniapp login app oauth permission

选择对应的登录方式后需要填写AppID等信息。

二、微信小程序第三方登录

1.判断是否登录

在微信小程序登录前需要判断是否登录,此时可以在App.vue中定义,因为App.vue中定义的变量和方法为全局变量和方法,可以在其他页面中可以调用,只需要用global关键字声明即可。

登录的一般原理为: 从本地缓存根据键获取到用户id和随机码等信息,再向服务端请求验证识别是否存在该用户。 随机码是为了提高数据接口的安全性建立的,除此之外也可以使用Redis、MemCache等实现安全保证。

先在App.vue中定义全局的判断是否登录的方法,如下:

<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>

再在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() {
		},
		methods: {
		}
	}
</script>

<style>

</style>

同时在pages目录下新建login.vue页面,如下:

<template>
	<view>
		login...
	</view>
</template>

<script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
		},
		onShow() {
		},
		onHide() {
		},
		methods: {
		}
	}
</script>

<style>

</style>

并将其添加进pages.json中,如下:

{
	"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函数里面得到。
	        }
	    ]
	}
}

显示:

uniapp login miniprogram is login
uniapp login miniprogram is login

显然,获取到了未登录的状态后,跳转到了登录页。

2.登录页面开发

登录需要判断所在平台、进行跨端开发,因此需要进行条件编译,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(res){
				console.log(res)
			}
		}
	}
</script>

<style>

</style>

显示:

uniapp login miniprogram clear cache
uniapp login miniprogram clear cache

可以看到,在成功登录后,会返回用户的相关信息; 在清除缓存并重新编译后,之前的登录状态不存在,需要重新登录。

登录后查看返回值res包含了一些不加密的基础信息,detail属性下面有iv属性,是加密算法的初始向量,可以解密得到信息,还可以作为是否授权登录的判断标准; rawData,不包括敏感信息的原始数据字符串,用于计算签名。 其中不包含openid和session_key等信息,需要进一步获取: 先通过uni.login(OBJECT)获取到code,即用户登录凭证; 再携带code,通过uni.request(OBJECT)获取到openid和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>

显示:

uniapp login miniprogram get openid sessionkey
uniapp login miniprogram get openid sessionkey

显然,此时获取到了openidsession 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等属性,只需要进行事件绑定就可以。

显示:

uniapp login app info
uniapp login app info

手机端显示:

uniapp login app info phone
uniapp login app info phone

显然,此时实现了条件编译,在不同的设备显示不同的按钮; 同时手机端点击时,控制台也输出信息。

先实现登录,需要获取服务商,判断是否安装微信,如果已安装则申请登录验证,如下:

<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>

显示:

uniapp login app login
uniapp login app login

手机端显示:

uniapp login app login phone
uniapp login app login phone

显然,实现了在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>

显示:

uniapp share miniprogram
uniapp share miniprogram

可以看到,实现了分享功能。

2.APP分享

APP中要实现分享,需要在manifest.json中进行配置,如下:

uniapp share app model setting
uniapp share app model setting

先实现分享纯文字,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>

显示:

uniapp share app text
uniapp share app text

手机端显示:

uniapp share app text phone
uniapp share app text phone

显然,控制台输出了分享成功的信息; 同时,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>

显示:

uniapp share app text image
uniapp share app text image

手机端显示:

uniapp share app text image phone
uniapp share app text image phone

显然,实现了分享图文到微信好友或微信群。

还可以分享到微信朋友圈,如下:

<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>

显示:

uniapp share app text image circle
uniapp share app text image circle

手机端显示:

uniapp share app text image circle phone
uniapp share app text image circle phone

已经实现了分享消息到朋友圈。

总结

第三方登录和分享是APP和小程序的基本功能,对于APP和小程序有不同的实现方式,相比较而言,APP实现更简单,都是其他功能的基础和起步。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-01-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 前言
  • 一、通用配置
    • 1.微信小程序端配置
      • 2.APP端配置
      • 二、微信小程序第三方登录
        • 1.判断是否登录
          • 2.登录页面开发
          • 三、APP第三方登录
          • 四、分享接口
            • 1.小程序分享
              • 2.APP分享
              • 总结
              相关产品与服务
              访问管理
              访问管理(Cloud Access Management,CAM)可以帮助您安全、便捷地管理对腾讯云服务和资源的访问。您可以使用CAM创建子用户、用户组和角色,并通过策略控制其访问范围。CAM支持用户和角色SSO能力,您可以根据具体管理场景针对性设置企业内用户和腾讯云的互通能力。
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档