微信web開發——微信登錄

本文主要介紹前端微信登錄獲取用戶信息的業務邏輯

一、業務實現

1.1判斷當前用戶是否登錄

如果有,證明當前用戶已登錄,返回主頁面

1.2判斷當前是否有code
1.2.1如果有,調用調用後端接口,返回用戶基本信息,同1.1
1.2.2如果無,調用微信api獲取code,獲取到code在調用用後端接口,同1.2.1

二、代碼如下(vue.js寫法)

index.js

init:function() {
	if(vm.getRequest().code!=undefined){ // 判斷是否是授權請求
		vm.getOpenid(vm.getRequest().code, app.codeUrl);
	} else {
		userInfo = JSON.parse(app.getItem(app.localKey.userInfo));  // 獲取本地用戶緩存(封裝)
		if(!userInfo){  // 判斷用戶是否已登錄
			vm.getCode();
			return;
		}
		app.go("loginMain");  // 跳轉登錄頁(封裝)
	}
},
getCode: function() { // 獲取code
	param = JSON.parse(app.getItem(app.localKey.param));
	if (!param) {
		param = {}
	}
	param.loginBack = 'loginMain.html'; // 緩存登錄頁,獲取code成功後返回用戶登錄頁進行數據綁定
	app.setItem(app.localKey.param, JSON.stringify(param)); // 設置本地緩存
	vm.redirect_uri = window.location.origin + app.sld + "view/index.html"; // 微信api請求回調地址
	wxApi.getCode(vm.appid, vm.urlencode(vm.redirect_uri)); // 微信api獲取code
},
getRequest:function () {  //獲取url的參數
  var url = location.search; //獲取url中"?"符後的字串  
   var theRequest = new Object();  
   if (url.indexOf("?") != -1) {  
      var str = url.substr(1);  
      strs = str.split("&");  
      for(var i = 0; i < strs.length; i ++) {  
         theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);  
      }  
   }  
   return theRequest;  
},
getOpenid: function(code, codeUrl) {  // 獲取用戶星星
	wxApi.getOpenid(code, codeUrl);  // 封裝的wxApi的JS
},			
urlencode: function(str) { // urlencode轉碼 防止url亂碼
	str = (str + '').toString();
	return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
	replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
},

wxapi.js

(function($, window) {
	window.wxApi = {
		getCode: function(appid, redirect_uri) {  // 獲取code
			var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirect_uri +
				"&response_type=code" + "&scope=snsapi_userinfo" + "&state=STATE#wechat_redirect";
			window.location.replace(url);
		},
		getOpenid: function(code, codeUrl) {  // 接口請求,獲取用戶信息
			var url = codeUrl + "weChat?code=" + code;
			$.ajax({
				type: 'GET',
				url: url,
				timeout: app.timeout,
				dataType: "json",
				success: function(r) {
					app.setItem(app.localKey.userInfo, JSON.stringify(r));
					param = JSON.parse(app.getItem(app.localKey.param));
					if (param.loginBack) {
						window.location.replace(param.loginBack);
					}
				},
				error: function(xhr, type, errorThrown) {
					$.toast(app.ajaxErrorTip);
				}
			});
		}

	}
})(mui, window);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章