웹 프론트엔드 uni-app uni-app 입문 튜토리얼 - 타사 로그인 및 공유

uni-app 입문 튜토리얼 - 타사 로그인 및 공유

Jan 18, 2021 pm 05:37 PM
uni-app

uni-app 입문 튜토리얼 - 타사 로그인 및 공유

추천(무료): uni-app development tutorial

기사 디렉토리

  • 서문
  • 1. 일반 구성
    • 1. 애플릿 구성
    • 2 .APP 측면 구성
  • 2. WeChat 애플릿의 타사 로그인
    • 1. 로그인 여부 결정
    • 2. 로그인 페이지 개발
  • 3. APP 타사 로그인
  • 4. 인터페이스 공유
    • 1. 미니 프로그램 공유
    • 2. 앱 공유
  • 요약

서문

이 글에서는 주로 앱 개발의 두 가지 기본 기능인 타사 로그인과 공유를 소개합니다. 로그인 일반 구성, WeChat 미니 프로그램 및 앱의 타사 로그인 방법, 채팅 및 Moments 공유, uni-app 사용에는 인터페이스와 구현 방법이 다릅니다.

1. 일반 구성

미니 프로그램과 APP 로그인 인터페이스가 다르기 때문에, 크로스 엔드 호환성 처리는 동시에 프런트 엔드와 같은 플랫폼에서 미니 프로그램을 수행해야 합니다. WeChat은 일반적으로 자신이 속한 호스트 프로그램의 제3자 로그인만 지원합니다. Weibo, QQ 등과 같은 다른 일반적인 제3자 로그인 방법은 포함할 수 없으므로 앱과 분리되어야 합니다.

1. 위챗 미니 프로그램 구성

위챗 미니 프로그램은 appid로 구성해야 하며, appid 및 관련 키를 받아야 합니다. .
appid를 얻은 후 Manifest.json을 편집하여 WeChat 애플릿 구성을 완료하거나 소스 코드 보기를 입력할 수 있습니다. 지침은 다음과 같습니다. 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

选择对应的登录方式后需要填写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

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

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

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

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

<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>
로그인 후 복사
로그인 후 복사
https://developers.weixin을 클릭할 수 있습니다. .qq.com/miniprogram/dev /api/open-api/user-info/wx.getUserInfo.html WeChat 공식 문서를 확인하세요. 🎜🎜HBuilder에서 제공하는 테스트 AppID를 사용할 때 Cannot read property 'forceUpdate' of undefine과 같은 오류가 보고될 수 있습니다. 이 경우 WeChat 공개 플랫폼 https:에 로그인할 수 있습니다. //developers.weixin.qq.com/community /welogin?redirect_url=%2Fsandbox에서 샌드박스 환경 테스트 번호의 🎜AppID 및 AppSecret🎜 정보를 신청하여 프로젝트 테스트에 사용하면 더 이상 오류가 출력되지 않습니다. 🎜🎜🎜2. 앱 측 구성 🎜🎜🎜앱 측에서는 WeChat, QQ, Weibo 등 다양한 타사 로그인 방법을 지원합니다. 해당 개발자를 신청하고 해당 앱 ID를 받아야 합니다.
해당 appid를 얻은 후 다음과 같이 매니페스트.json을 편집하고 시각적 작업을 수행하고 앱 모듈 구성을 선택하고 OAuth 인증 구성을 수행하고 필요한 로그인 방법(QQ, WeChat 등)을 선택합니다.
🎜🎜선택 후 필수 해당 로그인 방법 AppID 및 기타 정보를 입력하세요. 🎜🎜🎜 2. 위챗 미니 프로그램 제3자 로그인 🎜🎜🎜🎜1. 로그인 여부 결정 🎜🎜🎜 위챗 미니 프로그램에 로그인하기 전, 로그인 여부를 결정해야 합니다. App.vue에 정의되어 있으므로 App.vue에서 정의할 수 있습니다. 변수와 메서드는 🎜전역 변수 및 메서드🎜로, 다른 페이지에서 호출할 수 있으며 global로만 선언하면 됩니다. > 키워드. 🎜🎜로그인의 일반적인 원칙은 다음과 같습니다.
키에 따라 로컬 캐시에서 사용자 ID, 임의 코드 및 기타 정보를 가져온 다음 서버에 사용자 존재 여부를 확인하도록 요청합니다.
🎜Random code🎜는 데이터 인터페이스의 보안을 향상시키기 위해 확립되었습니다. 또한 Redis, MemCache 등을 사용하여 보안을 보장할 수도 있습니다. 🎜🎜먼저 App.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>
로그인 후 복사
로그인 후 복사
🎜 그런 다음 index.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>
로그인 후 복사
로그인 후 복사
🎜동시에 새 로그인을 생성합니다. 다음과 같이 페이지 디렉토리의 페이지를 확인하세요. 🎜
<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>
로그인 후 복사
로그인 후 복사
🎜 그리고 다음과 같이 페이지.json에 추가하세요. 🎜
<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>
로그인 후 복사
로그인 후 복사
🎜Display:
uniapp login miniprogram is login🎜🎜분명히 비로그인 상태를 얻은 후 로그인 페이지로 점프합니다. 🎜🎜🎜2. 로그인 페이지 개발🎜🎜🎜로그인에서는 플랫폼을 결정하고 크로스엔드 개발을 진행해야 하므로 🎜조건부 컴파일🎜이 필요합니다. 🎜
<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>
로그인 후 복사
로그인 후 복사
🎜Display:
uniapp 로그인 미니프로그램 캐시 지우기🎜🎜성공한 후에 볼 수 있습니다 로그인하면 사용자가 반환됩니다. 관련 정보;
캐시를 지우고 다시 컴파일한 후에는 이전 로그인 상태가 존재하지 않으므로 다시 로그인해야 합니다. 🎜🎜로그인 후 반환 값 res를 확인하세요. 여기에는 암호화되지 않은 일부 기본 정보가 포함되어 있습니다. 🎜암호화 알고리즘🎜의 초기 벡터인 🎜iv 속성🎜이 있습니다. 로그인 승인 여부를 결정하는 기준으로 사용됩니다.
서명을 계산하는 데 사용되는 민감한 정보를 제외한 원시 데이터 문자열입니다.
openid, session_key와 같은 추가 정보가 포함되어 있지 않습니다.
먼저 uni.login(OBJECT); <br> 그런 다음 코드를 운반하고 <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

显然,此时获取到了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 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 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

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

2.APP分享

APP中要实现分享,需要在manifest.json中进行配置,如下:
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 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 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 phone

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

总结

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

更多相关免费了解敬请关注uni_app教程栏目!

위 내용은 uni-app 입문 튜토리얼 - 타사 로그인 및 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

VSCode에서 uni-app을 개발하는 방법은 무엇입니까? (튜토리얼 공유) VSCode에서 uni-app을 개발하는 방법은 무엇입니까? (튜토리얼 공유) May 13, 2022 pm 08:11 PM

VSCode에서 uni-app을 개발하는 방법은 무엇입니까? 다음 기사에서는 VSCode에서 uni-app을 개발하는 방법에 대한 튜토리얼을 공유할 것입니다. 이것은 아마도 가장 훌륭하고 자세한 튜토리얼일 것입니다. 와서 살펴보세요!

uniapp을 사용하여 간단한 지도 탐색 개발 uniapp을 사용하여 간단한 지도 탐색 개발 Jun 09, 2022 pm 07:46 PM

uniapp을 사용하여 간단한 지도 탐색을 개발하는 방법은 무엇입니까? 이 기사는 간단한 지도를 만드는 데 도움이 되기를 바랍니다.

uniapp을 활용하여 스네이크 게임을 개발하는 방법에 대해 이야기해보겠습니다! uniapp을 활용하여 스네이크 게임을 개발하는 방법에 대해 이야기해보겠습니다! May 20, 2022 pm 07:56 PM

uniapp을 사용하여 스네이크 게임을 개발하는 방법은 무엇입니까? 다음 기사는 uniapp에서 Snake 게임을 구현하는 방법을 단계별로 설명합니다. 도움이 되기를 바랍니다.

uni-app vue3 인터페이스 요청을 캡슐화하는 방법 uni-app vue3 인터페이스 요청을 캡슐화하는 방법 May 11, 2023 pm 07:28 PM

uni-app 인터페이스, 전역 메서드 캡슐화 1. 루트 디렉터리에 api 파일을 생성하고 api 폴더에 api.js, baseUrl.js 및 http.js 파일을 생성합니다. 2.baseUrl.js 파일 코드 importdefault"https://XXXX .test03.qcw800.com/api/"3.http.js 파일 코드 내보내기 기능https(opts,data){lethttpDefaultOpts={url:opts.url,data:data,method:opts.method

uni-app 캘린더 플러그인을 개발하고 게시하는 방법을 단계별로 안내합니다. uni-app 캘린더 플러그인을 개발하고 게시하는 방법을 단계별로 안내합니다. Jun 30, 2022 pm 08:13 PM

이 글은 유니앱 캘린더 플러그인 개발 과정을 단계별로 안내하고, 다음 캘린더 플러그인 개발부터 출시까지 어떻게 진행되는지 소개하는 글이 여러분께 도움이 되길 바랍니다!

uniapp이 다중 선택 상자의 전체 선택 기능을 구현하는 방법을 설명하는 예 uniapp이 다중 선택 상자의 전체 선택 기능을 구현하는 방법을 설명하는 예 Jun 22, 2022 am 11:57 AM

이번 글에서는 다중 선택박스의 전체 선택 기능 구현과 관련된 이슈를 주로 정리한 uniapp 관련 지식을 소개합니다. 전체 선택 기능을 구현할 수 없는 이유는 체크박스의 체크된 필드가 동적으로 수정하면 인터페이스의 상태가 실시간으로 변경될 수 있지만 checkbox-group의 변경 이벤트는 트리거될 수 없습니다. 모두에게 도움이 되기를 바랍니다.

uniapp의 스크롤뷰 드롭다운 로딩에 대해 이야기해보겠습니다. uniapp의 스크롤뷰 드롭다운 로딩에 대해 이야기해보겠습니다. Jul 14, 2022 pm 09:07 PM

uniapp은 스크롤 보기 드롭다운 로딩을 어떻게 구현합니까? 다음 기사에서는 uniapp WeChat 애플릿 스크롤 보기의 드롭다운 로딩에 대해 설명합니다. 모든 사람에게 도움이 되기를 바랍니다.

uniapp이 전화 녹음 기능을 구현하는 방법에 대한 자세한 예(코드 포함) uniapp이 전화 녹음 기능을 구현하는 방법에 대한 자세한 예(코드 포함) Jan 05, 2023 pm 04:41 PM

이 기사는 uniapp에 대한 관련 지식을 제공합니다. 주로 uniapp을 사용하여 전화를 걸고 녹음을 동기화하는 방법을 소개합니다. 관심 있는 친구들이 꼭 읽어보시기 바랍니다.

See all articles