login.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. import { login,loginByWeChat,setPhone,bindWechat,updatePushId } from '@/api/user'
  2. import { qconfig } from '@/utils/config.js';
  3. import { navBack, registerIdCode,updateMsgDot,setSource } from '@/utils/common.js';
  4. import {isLogin} from '@/utils/common.js'
  5. let univerifyManager=null;
  6. let registrationID=uni.getStorageSync("registrationID");
  7. let userPhone="";
  8. let unionid="";
  9. let loginType=3;//1账号密码 2:微信登录 3:手机号一键登录
  10. let isMobileLoginFst=false; //标识是否先手机号登录且没有绑定微信;(该手机号用户没有微信unionId)
  11. let pages = '';
  12. let url = ''; //当前页页面实例
  13. // #ifdef APP-PLUS
  14. let source = 'app';
  15. // #endif
  16. // #ifndef APP-PLUS
  17. let source = '';
  18. // #endif
  19. export function showLoginPage(){
  20. pages = getCurrentPages();
  21. url = pages[ pages.length - 1];
  22. // #ifdef APP-PLUS
  23. if(qconfig!=undefined && qconfig.applyLogin){
  24. return;
  25. }
  26. if(!plus.runtime.isAgreePrivacy()) {
  27. if(url&&url.route=="pages/auth/login"){
  28. return;
  29. }
  30. uni.navigateTo({
  31. url: "/pages/auth/login"
  32. });
  33. return;
  34. }
  35. uni.showLoading({title:""});
  36. getRegistrationID();
  37. let that=this;
  38. console.log("----qxj 一键登录调用1-----");
  39. univerifyManager = uni.getUniverifyManager();
  40. //手机号一键登录时
  41. univerifyLogin(this);
  42. const loginCallBack = (res) => {
  43. // 获取一键登录弹框协议勾选状态
  44. univerifyManager.getCheckBoxState({success(res) {
  45. if(qconfig!=undefined){
  46. qconfig.applyLogin=false;
  47. }
  48. uni.hideLoading();
  49. if(!res.state){
  50. uni.showToast({title: "请同意服务条款和隐私政策",icon: 'none',position:'bottom'});
  51. return;
  52. }
  53. quickWechatLogin(false);
  54. // 关闭一键登录弹框
  55. univerifyManager.close();
  56. }
  57. });
  58. }
  59. // 订阅自定义按钮点击事件
  60. univerifyManager.onButtonsClick(loginCallBack);
  61. // 取消订阅自定义按钮点击事件
  62. //univerifyManager.offButtonsClick(loginCallBack);
  63. if(qconfig!=undefined){
  64. qconfig.applyLogin=true;
  65. }
  66. uni.hideLoading();
  67. // #endif
  68. // #ifdef H5
  69. if(String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger"){
  70. let url=window.location.href;
  71. //let urlPaths=url.split("/h5");
  72. let urlPaths=url.split("/pages");
  73. let pagePath="/pages"+urlPaths[1];
  74. uni.setStorageSync('beforLoginPage',pagePath);
  75. uni.navigateTo({
  76. url: "/pages/auth/h5WxLogin"
  77. });
  78. }
  79. else{
  80. if(url&&url.route=="pages/auth/login"){
  81. return;
  82. }
  83. uni.navigateTo({
  84. url: "/pages/auth/login"
  85. });
  86. }
  87. // #endif
  88. }
  89. const univerifyLogin=function(that){
  90. univerifyManager.login({
  91. provider: 'univerify',
  92. univerifyStyle: { // 自定义登录框样式
  93. fullScreen: true,
  94. authButton: {
  95. "title": "本机号码一键登录",
  96. "normalColor": "#FF5C03",
  97. "highlightColor": "#FF5C03",
  98. },
  99. otherLoginButton: {
  100. "title": "微信快捷登录",
  101. "visible": "false",
  102. },
  103. closeIcon: {
  104. "path": "static/image/icon_close.png",
  105. "width": "160px", //图标宽度 默认值:60px (HBuilderX 4.0支持)
  106. "height": "160px" //图标高度 默认值:60px (HBuilderX 4.0支持)
  107. },
  108. buttons: {
  109. "iconWidth": "60px", // 图标宽度(高度等比例缩放) 默认值:45px
  110. "list": [
  111. // {
  112. // "provider": "apple",
  113. // "iconPath": "/static/apple.png" // 图标路径仅支持本地图片
  114. // },
  115. {
  116. "provider": "weixin",
  117. "iconPath": "/static/image/login/weixin.png" // 图标路径仅支持本地图片
  118. }
  119. ]
  120. },
  121. privacyTerms: {
  122. "defaultCheckBoxState":false, // 条款勾选框初始状态 默认值: true
  123. "isCenterHint":false, //未勾选服务条款时点击登录按钮的提示是否居中显示 默认值: false (3.7.13+ 版本支持)
  124. "uncheckedImage":"", // 可选 条款勾选框未选中状态图片(仅支持本地图片 建议尺寸 24x24px)(3.2.0+ 版本支持)
  125. "checkedImage":"", // 可选 条款勾选框选中状态图片(仅支持本地图片 建议尺寸24x24px)(3.2.0+ 版本支持)
  126. "checkBoxSize":18, // 可选 条款勾选框大小
  127. "textColor": "#BBBBBB", // 文字颜色 默认值:#BBBBBB
  128. "termsColor": "#FF5C03", // 协议文字颜色 默认值: #5496E3
  129. "prefix": "我已阅读并同意", // 条款前的文案 默认值:“我已阅读并同意”
  130. "suffix": "并使用本机号码登录", // 条款后的文案 默认值:“并使用本机号码登录”
  131. "privacyItems": [ // 自定义协议条款,最大支持2个,需要同时设置url和title. 否则不生效
  132. {
  133. "url": "https://userapp.his.cdwjyyh.com/web/userAgreement", // 点击跳转的协议详情页面
  134. "title": "用户服务协议" // 协议名称
  135. },
  136. {
  137. "url": "https://userapp.his.cdwjyyh.com/web/privacyPolicy", // 点击跳转的协议详情页面
  138. "title": "隐私保护" // 协议名称
  139. }
  140. ]
  141. },
  142. },
  143. success(res){ // 登录成功
  144. // console.log("qxj univerify login:"+JSON.stringify(res.authResult)); // {openid:'登录授权唯一标识',access_token:'接口返回的 token'}
  145. uni.hideLoading();
  146. if(qconfig!=undefined){
  147. qconfig.applyLogin=false;
  148. }
  149. loginType=3;
  150. loginByUniverify(res.authResult,0);
  151. },
  152. fail(res){
  153. uni.hideLoading();
  154. if(qconfig!=undefined){
  155. qconfig.applyLogin=false;
  156. }
  157. if(res.code==30008){ //用户点击了自定义按钮
  158. uni.getCheckBoxState({
  159. success(res){
  160. if(!res.state){
  161. uni.showToast({title: "请同意服务条款和隐私政策",icon: 'none',position:'bottom'});
  162. return;
  163. }
  164. quickWechatLogin(false);
  165. },
  166. fail(res){
  167. console.log(res.errCode)
  168. console.log(res.errMsg)
  169. }
  170. });
  171. console.log("----qxj 一键登录调用2-----");
  172. }
  173. else if(res.code==30003){ //关闭验证界面
  174. return false;
  175. }
  176. else if(res.code==30005){ //预登录失败
  177. // uni.showToast({title: "一键登录失败请检查网络和SIM卡是否可用",icon: 'none',position:'bottom'});
  178. if(url&&url.route=="pages/auth/login"){
  179. return;
  180. }
  181. setTimeout(function() {
  182. uni.navigateTo({url: "/pages/auth/login"});
  183. }, 400);
  184. }
  185. }
  186. });
  187. };
  188. export function quickWechatLogin(isMobileLogin){
  189. isMobileLoginFst=isMobileLogin;
  190. loginType=2;
  191. uni.login({
  192. provider: "weixin",
  193. onlyAuthorize:true,
  194. success: async (res) => {
  195. let that=this;
  196. uni.showLoading({
  197. title:"处理中..."
  198. });
  199. if(isMobileLogin){
  200. bindWechatAct(userPhone,res.code);
  201. }
  202. else{
  203. const params={"code":res.code,"loginDevice":getLoginDevice(),"jpushId":registrationID,"source":plus.runtime.channel || source};
  204. loginByWeChatAct(params);
  205. }
  206. },
  207. fail: (err) => {
  208. console.log('login fail:', JSON.stringify(err));
  209. // 未开通
  210. if (err.code == 1000) {
  211. uni.showModal({
  212. title: '登录失败',
  213. content: `${err.errMsg}\n,错误码:${err.code}`,
  214. confirmText: '开通指南',
  215. cancelText: '确定',
  216. success: (res) => {
  217. if (res.confirm) {
  218. setTimeout(() => {
  219. plus.runtime.openWeb('https://ask.dcloud.net.cn/article/37965')
  220. }, 500)
  221. }
  222. }
  223. });
  224. return;
  225. }
  226. // 一键登录预登陆失败
  227. if (err.code == '30005') {
  228. uni.showModal({
  229. showCancel: false,
  230. title: '预登录失败',
  231. content: err.errMsg
  232. });
  233. return;
  234. }
  235. // 一键登录用户关闭验证界面
  236. if (err.code != '30003') {
  237. uni.showModal({
  238. showCancel: false,
  239. title: '登录失败',
  240. content: JSON.stringify(err)
  241. });
  242. }
  243. },
  244. complete: () => {
  245. }
  246. });
  247. };
  248. export function loginByWeChatAct(params){
  249. loginByWeChat(params).then(res => {
  250. if(res.code==200){
  251. if(res.user!=null){
  252. uni.hideLoading();
  253. uni.setStorageSync('AppToken',res.token);
  254. uni.setStorageSync('userInfo',JSON.stringify(res.user));
  255. uni.$emit('refreshUserInfo',{ "isFirst":res.isFirst });
  256. uni.$emit('showHealthButler');
  257. uni.closeAuthView();
  258. if(res.isFirst){ //未完成新手任务
  259. uni.navigateTo({ url: '/pages/user/integral/points' });
  260. }
  261. else {
  262. goPage()
  263. }
  264. }
  265. else{
  266. unionid=res.unionid;
  267. if(isMobileLoginFst){ //若先点击手机号登录且没有绑定微信
  268. bindWechatAct(userPhone,unionid);
  269. }else{
  270. if(res.isNew){ //是否绑定手机号
  271. bindMobile();
  272. }
  273. }
  274. }
  275. }
  276. else{
  277. uni.hideLoading();
  278. uni.showToast({title: res.msg,icon: 'none'});
  279. }
  280. },
  281. rej => {}
  282. );
  283. }
  284. export function bindMobile(){
  285. // #ifdef APP-PLUS
  286. //uni.showLoading({title:""});
  287. uni.login({
  288. provider: 'univerify',
  289. univerifyStyle: { // 自定义登录框样式
  290. fullScreen: false,
  291. authButton: {
  292. "title": "绑定手机号",
  293. "normalColor": "#FF5C03",
  294. "highlightColor": "#FF5C03",
  295. },
  296. privacyTerms: {
  297. "defaultCheckBoxState":true, // 条款勾选框初始状态 默认值: true
  298. "isCenterHint":false, //未勾选服务条款时点击登录按钮的提示是否居中显示 默认值: false (3.7.13+ 版本支持)
  299. "uncheckedImage":"", // 可选 条款勾选框未选中状态图片(仅支持本地图片 建议尺寸 24x24px)(3.2.0+ 版本支持)
  300. "checkedImage":"", // 可选 条款勾选框选中状态图片(仅支持本地图片 建议尺寸24x24px)(3.2.0+ 版本支持)
  301. "checkBoxSize":18, // 可选 条款勾选框大小
  302. "textColor": "#BBBBBB", // 文字颜色 默认值:#BBBBBB
  303. "termsColor": "#FF5C03", // 协议文字颜色 默认值: #5496E3
  304. "prefix": "我已阅读并同意", // 条款前的文案 默认值:“我已阅读并同意”
  305. "suffix": "并使用本机号码登录", // 条款后的文案 默认值:“并使用本机号码登录”
  306. "privacyItems": [ // 自定义协议条款,最大支持2个,需要同时设置url和title. 否则不生效
  307. ]
  308. },
  309. },
  310. success(res){ //
  311. // console.log("qxj univerify login:"+JSON.stringify(res.authResult)); // {openid:'登录授权唯一标识',access_token:'接口返回的 token'}
  312. loginByUniverify(res.authResult,1);
  313. },
  314. fail(res){
  315. uni.hideLoading();
  316. uni.closeAuthView();
  317. if(res.errCode==30005){ //预登录失败
  318. //uni.showToast({title: "一键登录失败请检查网络和SIM卡是否可用",icon: 'none',position:'bottom'});
  319. if(url&&url.route=="pages/auth/login"){
  320. return;
  321. }
  322. //setTimeout(function() {
  323. uni.navigateTo({url: "/pages/auth/login"});
  324. //}, 1800);
  325. }
  326. console.log("qxj failRes:"+JSON.stringify(res));
  327. }
  328. });
  329. console.log("----qxj 一键登录调用3-----");
  330. // #endif
  331. // #ifdef H5
  332. if(url&&url.route=="pages/auth/login"){
  333. return;
  334. }
  335. uni.navigateTo({
  336. url: "/pages/auth/login"
  337. });
  338. // #endif
  339. };
  340. export function loginByUniverify(authResult,type){
  341. uniCloud.callFunction({
  342. name: 'loginByMobile', // 你的云函数名称
  343. data: {
  344. access_token: authResult.access_token, // 客户端一键登录接口返回的access_token
  345. openid:authResult.openid // 客户端一键登录接口返回的openid
  346. }
  347. }).then(res => {
  348. if(res.result.errCode==0){
  349. userPhone=res.result.phoneNumber;
  350. if(type==0){ //手机号一键登录
  351. loginActionAct();
  352. }else{ //微信登录绑定手机号
  353. setPhoneAct(userPhone,unionid);
  354. }
  355. }else{
  356. uni.showToast({title:res.result.message,icon: 'none' });
  357. }
  358. }).catch(err=>{
  359. // 处理错误
  360. console.error('调用云函数失败:',err);
  361. // 详细记录错误信息
  362. console.error('错误信息:', err.errMsg);
  363. })
  364. }
  365. export function loginActionAct(){
  366. if (loginType==3 && userPhone==null) {
  367. uni.showToast({title: "请授权手机号登录",icon: 'none'});
  368. return
  369. }
  370. var data = {
  371. phone:userPhone,
  372. jpushId:registrationID,
  373. loginType:loginType,
  374. loginDevice:getLoginDevice(),
  375. source:plus.runtime.channel || source
  376. };
  377. var that=this;
  378. uni.showLoading({
  379. title:"处理中..."
  380. });
  381. login(data).then(res => {
  382. console.log("qxj res:"+JSON.stringify(res));
  383. uni.hideLoading();
  384. if(res.code==200){
  385. if(res.isNew){
  386. userPhone=res.phone;
  387. quickWechatLogin(true);
  388. return;
  389. }
  390. uni.setStorageSync('AppToken',res.token);
  391. uni.setStorageSync('userInfo',JSON.stringify(res.user));
  392. uni.$emit('showHealthButler');
  393. uni.closeAuthView();
  394. if(res.isFirst){
  395. // #ifdef APP-PLUS
  396. if(plus.runtime.channel=="baidu"){ //获取百度渠道标识
  397. let bdCmdType=uni.getStorageSync("bdCmdType");
  398. if(bdCmdType!=null && parseInt(bdCmdType)<1){
  399. registerIdCode("register",1,0,res.user.userId); //注册
  400. }
  401. }
  402. // #endif
  403. uni.navigateTo({ url: '/pages/user/integral/points' });
  404. } else {
  405. goPage()
  406. }
  407. }
  408. else{
  409. uni.showToast({title: res.msg,icon: 'none'});
  410. }
  411. },
  412. rej => {}
  413. );
  414. }
  415. export function setPhoneAct(phone,unionId,){
  416. let params={"phone":phone,"unionId":unionId,"jpushId":registrationID,"source":plus.runtime.channel || source};
  417. setPhone(params).then(res => {
  418. uni.hideLoading();
  419. if(res.code==200){
  420. uni.setStorageSync('AppToken',res.token);
  421. uni.setStorageSync('userInfo',JSON.stringify(res.user));
  422. uni.$emit('showHealthButler');
  423. uni.closeAuthView();
  424. goPage()
  425. // #ifdef APP-PLUS
  426. // const jyJPush = uni.requireNativePlugin('JY-JPush');
  427. // jyJPush.setJYJPushAlias({userAlias: registrationID}, result=> {
  428. // console.log("qxj userAlias "+JSON.stringify(result));
  429. // });
  430. // #endif
  431. }
  432. else{
  433. uni.showToast({title: res.msg,icon: 'none'});
  434. }
  435. },
  436. rej => {}
  437. );
  438. }
  439. export function bindWechatAct(phone,code){
  440. let params={"phone":phone,"code":code,"jpushId":registrationID,"source":plus.runtime.channel || source};
  441. bindWechat(params).then(res => {
  442. uni.hideLoading();
  443. console.log("qxj bindWeChat res:"+JSON.stringify(res));
  444. if(res.code==200){
  445. uni.setStorageSync('AppToken',res.token);
  446. uni.setStorageSync('userInfo',JSON.stringify(res.user));
  447. uni.$emit('showHealthButler');
  448. uni.closeAuthView();
  449. goPage()
  450. // #ifdef APP-PLUS
  451. const jyJPush = uni.requireNativePlugin('JY-JPush');
  452. // jyJPush.setJYJPushAlias({userAlias: registrationID}, result=> {
  453. // console.log("qxj userAlias "+JSON.stringify(result));
  454. // });
  455. // #endif
  456. }
  457. else{
  458. uni.showToast({title: res.msg,icon: 'none'});
  459. setTimeout(function() {
  460. uni.closeAuthView();
  461. }, 1800);
  462. }
  463. },
  464. rej => {}
  465. );
  466. }
  467. export function getRegistrationID(type) {
  468. // #ifdef APP-PLUS
  469. registrationID = uni.getStorageSync("registrationID");
  470. const needUpdate = type === 'update' || !registrationID;
  471. if (needUpdate&&plus.runtime.isAgreePrivacy()) {
  472. uni.getPushClientId({success: res => {
  473. registrationID = res.cid
  474. uni.setStorageSync("registrationID",res.cid);
  475. if(type == 'update'&&isLogin()) {
  476. upPushClientId(res.cid)
  477. }
  478. },
  479. fail:(err)=> {
  480. console.log("getRegistrationID error:",err)
  481. }
  482. });
  483. }
  484. // #endif
  485. }
  486. function getLoginDevice(){
  487. let loginDevice = "";
  488. // #ifdef APP-PLUS
  489. if(plus.runtime.isAgreePrivacy()) {
  490. let devinfo=uni.getDeviceInfo();
  491. if(devinfo!=null){
  492. loginDevice += devinfo.deviceBrand ? devinfo.deviceBrand : "";
  493. loginDevice += devinfo.deviceModel ? " " + devinfo.deviceModel : "";
  494. loginDevice += devinfo.system ? " " + devinfo.system : "";
  495. }
  496. }
  497. // #endif
  498. return loginDevice;
  499. }
  500. function goPage() {
  501. pages = getCurrentPages();
  502. url = pages[ pages.length - 1];
  503. if(univerifyManager) {
  504. univerifyManager.close();
  505. uni.closeAuthView();
  506. univerifyManager = null
  507. }
  508. const openUrl = uni.getStorageSync("openUrl")
  509. if(openUrl) {
  510. uni.navigateTo({
  511. url: openUrl,
  512. success: function(res) {
  513. uni.removeStorageSync("openUrl")
  514. }
  515. })
  516. } else {
  517. if(pages.length == 1) {
  518. uni.reLaunch({
  519. url: '../course/index',
  520. //url: '../course/video/living-app',
  521. animationType: 'none',
  522. animationDuration: 2000
  523. })
  524. } else {
  525. navBack()
  526. }
  527. }
  528. updateMsgDot()
  529. setSource()
  530. }
  531. export function upPushClientId(pushId) {
  532. updatePushId({pushId:pushId})
  533. }