一、在微信平台上申請appid、appsecret。
二、app --》 manifest.json--》SDK配置(填寫申請好的appid和appsecret)
三、在登錄頁,點擊微信登錄按鈕,若綁定微信,則免賬號密碼登錄直接跳轉到首頁;若未綁定,則彈出未綁定微信。
// 微信授權登錄對象 var aweixin=null; // 調用plus.oauth.getServices獲取保存 // 當前環境支持的所有授權登錄對象 var auths = {}; mui.plusReady(function() { // 獲取鑒權服務 getService(); }) // 獲取登錄授權認證服務列表,單獨保存微信登錄授權對象 // 5+APP在plusready事件中調用,uni-app在vue頁面的onLoad中調用 function getService(){ plus.oauth.getServices(function(services){ for(var i=0;i<services.length;i++){ auths[services[i].id] = services[i]; } aweixin = auths['weixin']; }, function(e){ plus.nativeUI.alert("獲取登錄授權服務列表失敗:"+JSON.stringify(e)); } ); } //wx登錄
document.getElementById('wxdenglu').addEventListener('tap',function(){ plus.nativeUI.showWaiting("正在登錄中...",{padlock: true}); if(!aweixin.authResult){ authLogin().then(res=>{ wxLogin()//調用自定義的登錄接口 }).catch(res=>{ plus.nativeUI.closeWaiting(); }) }else{ wxLogin()//調用自定義的登錄接口 } });
四、用賬號密碼登進首頁時,判斷是否綁定微信,若為綁定微信,則提示讓其綁定微信。
五、微信綁定和解綁。
// 微信授權登錄對象 // 調用plus.oauth.getServices獲取保存 var aweixin=null; // 當前環境支持的所有授權登錄對象 var auths = {}; mui.plusReady(function(){ // 獲取鑒權服務 getService() }); //wx綁定 function weixinBind(){ plus.nativeUI.showWaiting("正在綁定中...",{padlock: true}); if(!aweixin.authResult){ authorize().then(res=>{ wxBind(1,aweixin.authResult.openid) }).catch(res=>{ plus.nativeUI.closeWaiting(); }) }else{ wxBind(1,aweixin.authResult.openid) } }; //wx解綁 function weixinUnBind(){ plus.nativeUI.showWaiting("正在解綁中...",{padlock: true}); wxBind(2,"") } // 獲取登錄授權認證服務列表,單獨保存微信登錄授權對象 // 5+APP在plusready事件中調用,uni-app在vue頁面的onLoad中調用 function getService(){ plus.oauth.getServices(function(services){ for(var i=0;i<services.length;i++){ auths[services[i].id] = services[i]; } aweixin = auths['weixin']; }, function(e){ plus.nativeUI.alert("獲取登錄授權服務列表失敗:"+JSON.stringify(e)); } ); } // 獲取微信登錄授權對象后可進行授權操作 function authorize(){ return new Promise(function (resolve, reject) { if(!aweixin){ plus.nativeUI.alert("當前環境不支持微信登錄"); return; } aweixin.authorize(function(e){ // plus.nativeUI.alert("授權成功:"+JSON.stringify(e)); authLogin().then(res=>{ resolve(res); }); }, function(e){ // plus.nativeUI.alert("授權失敗:"+JSON.stringify(e)); plus.nativeUI.closeWaiting(); reject(e); }, {scope:'snsapi_userinfo',state:'authorize test'}); }) } // 獲取微信登錄授權對象后可進行登錄認證操作 function authLogin(){ return new Promise(function (resolve, reject) { if(!aweixin){ plus.nativeUI.alert("當前環境不支持微信登錄"); return; } if(!aweixin.authResult){ aweixin.login(function(e){ // plus.nativeUI.alert("登錄認證成功!"+JSON.stringify(e)); resolve(e); }, function(e){ reject(e); } ); }else{ // plus.nativeUI.alert("已經登錄認證!"); } }) }
