sns-login-sdk
Version:
统一身份登录 SDK - 基于自定义协议调用桌面应用程序进行身份认证
2 lines (1 loc) • 2.42 kB
JavaScript
import{v7 as i}from"uuid";class t{constructor(i={}){const{options:t={},callbacks:s={}}=i;this.options={pollingTimeout:6e5,pollingInterval:1e3,baseURL:"http://localhost:3500",apiEndpoints:{getVp:"/get/vp"},baseUrl:"undefined"!=typeof window?window.location.origin:"",type:1,...t},this.uuidString="",this.startTime=0,this.isPolling=!1,this.pollingTimer=null,this.callbacks={onLoading:i=>{},onSuccess:i=>{},onError:i=>{},onMessage:(i,t="info")=>{},...s},this.login=this.login.bind(this),this.stopPolling=this.stopPolling.bind(this)}async login(){try{this.uuidString=i().slice(0,32),this.callbacks.onLoading(!0),await this.invokeDesktopApp()}catch(i){this.callbacks.onError(i),this.callbacks.onLoading(!1)}}async invokeDesktopApp(){try{const i=this.uuidString.substring(0,32),t=`tdid://getVP?json=${JSON.stringify({uuid:i,baseUrl:this.options.baseUrl,type:this.options.type})}`,s=document.createElement("iframe");s.style.display="none",s.src=t,document.body.appendChild(s),setTimeout(()=>{document.body.removeChild(s)},1e3),this.startPolling()}catch(i){this.callbacks.onError(i),this.callbacks.onLoading(!1)}}startPolling(){this.startTime=Date.now(),this.isPolling=!0,this.waitForVP()}async waitForVP(){if(this.isPolling){if(Date.now()-this.startTime>=this.options.pollingTimeout)return this.stopPolling(),this.callbacks.onMessage("获取签名失败","error"),void this.callbacks.onLoading(!1);try{const i=await this.apiGetVp(this.uuidString);if(i){if("refuse"===i)return this.stopPolling(),this.callbacks.onMessage("客户端正忙,请稍后再试","error"),void this.callbacks.onLoading(!1);let t=null;if(i?.tokenValue?t=i.tokenValue:i?.data?.tokenValue&&(t=i.data.tokenValue),t)return this.stopPolling(),this.callbacks.onSuccess(t),void this.callbacks.onLoading(!1)}this.pollingTimer=setTimeout(()=>{this.waitForVP()},this.options.pollingInterval)}catch(i){this.pollingTimer=setTimeout(()=>{this.waitForVP()},this.options.pollingInterval)}}}stopPolling(){this.isPolling=!1,this.pollingTimer&&(clearTimeout(this.pollingTimer),this.pollingTimer=null)}async apiGetVp(i){const t=`${this.options.baseURL}${this.options.apiEndpoints.getVp}?uuid=${i}`,s=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}destroy(){this.stopPolling(),this.callbacks={}}}function s(i={}){return new t(i)}export{s as createSnsLogin,t as default};