uniapp 获取各种小程序code

各种小程序在进入小程序是  都需要去获取code 才能拿到基础信息,自己记录一下用uniapp 开发小程序是获取 微信小程序、百度小程序、头条小程序、支付宝小程序的code

Vue.prototype.$global = {
	appLogin() {
		return new Promise((resole, reject) => {
			var that = this;
			var wxLoginUrl = app.globalData.url + "/login/getUserOpenId";  //获取code接口
			uni.getProvider({
				service: 'oauth',
				success(res) {
					//微信code
					if (res.provider.includes('weixin') ) {   // 判断是微信
						uni.login({
							success(loginRes) {
								if(loginRes.code){
									uni.request({
										url: wxLoginUrl,
										method: "POST",
										data: {
											code:loginRes.code
										},
										success: function (res) {
											let info = res.data.data
											if(res.data.status==1){
												uni.setStorageSync("loginType",'0');
												uni.setStorageSync("open_id",info.open_id);  //获取的open_id
												uni.setStorageSync("sessionKey",info.sessionKey); // 获取的sessionKey
											}
										}
									})
								}
								
							}
						})
					}
					//百度code   百度不需要接口 直接跳去百度给的接口即可
					if(res.provider.includes('baidu')){
						uni.login({
							provider: uni.getStorageSync('provider'),
							success: (res) => {
								uni.request({
									url: "https://spapi.baidu.com/oauth/jscode2sessionkey",
									method: "POST",
									data: {
										code:res.code,
										client_id:'aa4pFKIEfGjHbish6HzXBnlAK2tMbtUS',
										sk:'u3K5GMEuvdhouGZwF6j4nq8nv9E42WqQ',
									},
									success: function (res) {
										uni.setStorageSync("loginType",'1');
										uni.setStorageSync("open_id",res.data.openid);
										uni.setStorageSync("sessionKey",res.data.session_key);
									}
								})
							}
						})	
					}
					//头条code
					if(res.provider.includes('toutiao')){

						// var loginUrl =  接口路劲
						uni.login({
							// provider: uni.getStorageSync('provider'),
							success: (res) => {
								
								uni.request({
									url: loginUrl,
									method: "POST",
									data: {
										code:res.code,
									},
									success: function (res) {
										uni.setStorageSync("loginType",'2');
										uni.setStorageSync("open_id",res.data.data.openid);
										uni.setStorageSync("sessionKey",res.data.data.session_key);
									}
								})
							}
						})	   
					};
					//支付宝登录
					if(res.provider.includes('alipay')){

						// var loginUrl =  接口路劲
						uni.login({
							scopes: 'auth_base', //进入支付宝不弹出授权窗口
							success: (res) => {
								uni.request({
									url: loginUrl,
									method: "POST",
									data: {
										code:res.authCode,
									},
									success: function (res) {
										uni.setStorageSync("loginType",'3');//支付时候判断是什么小程序
										uni.setStorageSync("open_id",res.data.data.open_id);
										uni.setStorageSync("sessionKey",res.data.data.sessionKey);
									}
								})
								
							}
							
						})	
					};
				}
			});
		})
	}

}

 

你可能感兴趣的:(uniapp,小程序)