uni-quick-login.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. <template>
  2. <view>
  3. <view class="quick-login-box">
  4. <view class="item" v-for="(item,index) in servicesList" :key="index"
  5. @click="item.path?to(item.path):login_before(item.id,false)">
  6. <image class="logo" :src="item.logo" mode="widthFix"></image>
  7. <text class="login-title">{{item.text}}</text>
  8. </view>
  9. </view>
  10. <!-- #ifdef MP-WEIXIN -->
  11. <uni-user-profile @next="doUserProfileNext" ref="userProfile"></uni-user-profile>
  12. <!-- #endif -->
  13. </view>
  14. </template>
  15. <script>
  16. import {
  17. initVueI18n
  18. } from '@dcloudio/uni-i18n'
  19. import messages from './i18n/index.js'
  20. const {
  21. t
  22. } = initVueI18n(messages)
  23. import {
  24. mapGetters,
  25. mapMutations
  26. } from 'vuex';
  27. //前一个窗口的页面地址。控制点击切换快捷登录方式是创建还是返回
  28. import loginSuccess from '@/subpages/ucenter/login-page/common/loginSuccess.js';
  29. const db = uniCloud.database();
  30. const usersTable = db.collection('uni-id-users')
  31. let allServicesList = []
  32. export default {
  33. computed: {
  34. loginConfig() {
  35. return getApp().globalData.config.router.login
  36. },
  37. agreements() {
  38. return getApp().globalData.config.about.agreements || []
  39. }
  40. },
  41. data() {
  42. return {
  43. servicesList: [{
  44. "id": "username",
  45. "text": t('accountLogin'),
  46. "logo": "/static/czzn-img/login/user.png",
  47. "path": "/subpages/ucenter/login-page/pwd-login/pwd-login"
  48. },
  49. {
  50. "id": "smsCode",
  51. "text": t('SMSLogin'),
  52. "logo": "/static/czzn-img/login/sms.png",
  53. "path": "/subpages/ucenter/login-page/index/index?type=smsCode"
  54. },
  55. {
  56. "id": "weixin",
  57. "text": t('wechatLogin'),
  58. "logo": "/static/czzn-img/login/wechat.png",
  59. },
  60. {
  61. "id": "apple",
  62. "text": t('appleLogin'),
  63. "logo": "/static/czzn-img/login/apple.png",
  64. },
  65. {
  66. "id": "univerify",
  67. "text": t('oneClickLogin'),
  68. "logo": "/static/czzn-img/login/univerify.png",
  69. },
  70. {
  71. "id": "qq",
  72. "text": t('QQLogin'), //暂未提供该登录方式的接口示例
  73. "logo": "/static/czzn-img/login/univerify.png",
  74. },
  75. {
  76. "id": "xiaomi",
  77. "text": t('xiaomiLogin'), //暂未提供该登录方式的接口示例
  78. "logo": "/static/czzn-img/login/univerify.png",
  79. },
  80. {
  81. "id": "sinaweibo",
  82. "text": t('weibo'), //暂未提供该登录方式的接口示例
  83. "logo": "/static/czzn-img/login/univerify.png",
  84. }
  85. ],
  86. config: {},
  87. univerifyStyle: { //一键登录弹出窗的样式配置参数
  88. "fullScreen": true, // 是否全屏显示,true表示全屏模式,false表示非全屏模式,默认值为false。
  89. "backgroundColor": "#ffffff", // 授权页面背景颜色,默认值:#ffffff
  90. "buttons": { // 自定义登录按钮
  91. "iconWidth": "45px", // 图标宽度(高度等比例缩放) 默认值:45px
  92. "list": []
  93. },
  94. "privacyTerms": {
  95. "defaultCheckBoxState": false, // 条款勾选框初始状态 默认值: true
  96. "textColor": "#BBBBBB", // 文字颜色 默认值:#BBBBBB
  97. "termsColor": "#5496E3", // 协议文字颜色 默认值: #5496E3
  98. "prefix": "我已阅读并同意", // 条款前的文案 默认值:“我已阅读并同意”
  99. "suffix": "并使用本机号码登录", // 条款后的文案 默认值:“并使用本机号码登录”
  100. "privacyItems": []
  101. }
  102. }
  103. }
  104. },
  105. watch: {
  106. agree(agree) {
  107. this.univerifyStyle.privacyTerms.defaultCheckBoxState = agree
  108. }
  109. },
  110. props: {
  111. agree: {
  112. type: Boolean,
  113. default () {
  114. return false
  115. }
  116. }
  117. },
  118. async created() {
  119. let servicesList = this.servicesList
  120. //去掉配置中不存在的 注意,在/common/appInit.js中已清除有配置但设备环境不支持的登录项
  121. servicesList = servicesList.filter(item => this.loginConfig.includes(item.id))
  122. //处理一键登录
  123. if (this.loginConfig.includes('univerify')) {
  124. this.univerifyStyle.privacyTerms.privacyItems = this.agreements
  125. //设置一键登录功能底下的快捷登录按钮
  126. servicesList.forEach(({
  127. id,
  128. logo,
  129. path
  130. }) => {
  131. if (id != 'univerify') {
  132. this.univerifyStyle.buttons.list.push({
  133. "iconPath": logo,
  134. "provider": id,
  135. // path
  136. })
  137. }
  138. })
  139. }
  140. console.log(servicesList);
  141. //如果当前页面为默认登录界面。当前第一优先级的“微信和苹果登录”要隐藏,因为他已经被渲染在默认登录界面顶部
  142. if (
  143. this.getRoute(1) == '/subpages/ucenter/login-page/index/index' && ['weixin', 'apple'].includes(this
  144. .loginConfig[0])
  145. ) {
  146. servicesList = servicesList.filter(item => item.id != this.loginConfig[0])
  147. }
  148. //去掉当前页面对应的登录选项
  149. this.servicesList = servicesList.filter(item => {
  150. let path = item.path ? item.path.split('?')[0] : '';
  151. return path != this.getRoute(1)
  152. })
  153. console.log('servicesList', servicesList, this.servicesList);
  154. },
  155. mounted() {},
  156. methods: {
  157. ...mapMutations({
  158. setUserInfo: 'user/login'
  159. }),
  160. getRoute(n = 0) {
  161. let pages = getCurrentPages();
  162. // console.log('route-pages-length', pages.length);
  163. if (n > pages.length) {
  164. return ''
  165. }
  166. return '/' + pages[pages.length - n].route
  167. },
  168. to(path) {
  169. console.log('比较', this.getRoute(1),this.getRoute(2), path)
  170. if(this.getRoute(1) == path.split('?')[0] && this.getRoute(1) == '/subpages/ucenter/login-page/index/index'){
  171. //如果要被打开的页面已经打开,且这个页面是 /pages/ucenter/login-page/index/index 则把类型参数传给他
  172. let type = path.split('?')[1].split('=')[1]
  173. uni.$emit('setLoginType',type)
  174. }else if(this.getRoute(2) == path) { // 如果上一个页面就是,马上要打开的页面,直接返回。防止重复开启
  175. uni.navigateBack();
  176. }else if(this.getRoute(1) != path) {
  177. uni.navigateTo({
  178. url: path,
  179. animationType: 'slide-in-left'
  180. })
  181. }else{
  182. console.log('出乎意料的情况,path:'+path);
  183. }
  184. },
  185. login_before(type, navigateBack = true) {
  186. console.log(type);
  187. if (!this.agree && type != 'univerify') {
  188. return uni.showToast({
  189. title: t('noAgree'),
  190. icon: 'none'
  191. });
  192. }
  193. uni.showLoading({mask: true})
  194. if (type == 'univerify' && uni.getUniverifyManager) {
  195. let univerifyManager = uni.getUniverifyManager()
  196. console.log('是新版');
  197. let onButtonsClickFn = async res =>{
  198. console.log('点击了第三方登录,provider:',res, res.provider,this.univerifyStyle.buttons.list);
  199. //同步一键登录弹出层隐私协议框是否打勾
  200. let agree = (await uni.getCheckBoxState())[1].state
  201. console.log('agree',agree);
  202. uni.$emit('setAgreementsAgree', agree)
  203. let {
  204. path
  205. } = this.univerifyStyle.buttons.list[res.index]
  206. console.log('path', path,this.getRoute(1));
  207. if (path) {
  208. this.to(path)
  209. closeUniverify()
  210. } else {
  211. if(agree){
  212. closeUniverify()
  213. setTimeout(() => {
  214. console.log('login_before');
  215. this.login_before(res.provider)
  216. }, 500)
  217. }else{
  218. console.log(t('noAgree'));
  219. uni.showToast({
  220. title: t('noAgree'),
  221. icon: 'none'
  222. });
  223. }
  224. }
  225. }
  226. function closeUniverify(){
  227. uni.hideLoading()
  228. univerifyManager.close()
  229. // 取消订阅自定义按钮点击事件
  230. univerifyManager.offButtonsClick(onButtonsClickFn)
  231. }
  232. // 订阅自定义按钮点击事件
  233. univerifyManager.onButtonsClick(onButtonsClickFn)
  234. // 调用一键登录弹框
  235. return univerifyManager.login({
  236. "univerifyStyle": this.univerifyStyle,
  237. success:res=> {
  238. console.log('login success', res)
  239. this.login(res.authResult, 'univerify')
  240. },
  241. fail(err) {
  242. uni.showToast({
  243. title: JSON.stringify(err),
  244. icon: 'none'
  245. });
  246. },
  247. complete(e){
  248. uni.hideLoading()
  249. // 取消订阅自定义按钮点击事件
  250. univerifyManager.offButtonsClick(onButtonsClickFn)
  251. }
  252. })
  253. }
  254. uni.login({
  255. "provider": type,
  256. "onlyAuthorize": true, //请勿直接使用前端获取的unionid或openid直接用于登录,前端的数据都是不可靠的
  257. "univerifyStyle": this.univerifyStyle,
  258. complete: (e) => {
  259. console.log(e);
  260. uni.hideLoading()
  261. },
  262. success: async e => {
  263. console.log(e);
  264. if (type == 'apple') {
  265. let res = await this.getUserInfo({
  266. provider: "apple"
  267. })
  268. Object.assign(e.authResult, res.userInfo)
  269. }
  270. this.login(type == 'weixin' ? e.code : e.authResult, type)
  271. },
  272. fail: async (err) => {
  273. console.log(err);
  274. // 以下代码为兼容旧版(HBuilderX3.2.13之前)HBuilderX3.2.13以上版本可直接删除
  275. if (type == 'univerify'&& !uni.getUniverifyManager) {
  276. if (err.metadata && err.metadata.error_data) {
  277. uni.showToast({
  278. title: t('oneClickLogin') + ":" + err.metadata.error_data,
  279. icon: 'none'
  280. });
  281. }
  282. if (err.errMsg) {
  283. uni.showToast({
  284. title: t('oneClickLogin') + ":" + err.errMsg,
  285. icon: 'none'
  286. });
  287. }
  288. switch (err.errCode) {
  289. case 30002:
  290. console.log('在一键登录界面,点击其他登录方式');
  291. break;
  292. case 30003:
  293. console.log('关闭了登录');
  294. if (navigateBack) {
  295. uni.navigateBack()
  296. }
  297. break;
  298. case 30006:
  299. uni.showModal({
  300. title: t('loginErr'),
  301. content: err.metadata.error_data,
  302. showCancel: false,
  303. confirmText: t('gotIt'),
  304. });
  305. break;
  306. case "30008":
  307. console.log('点击了第三方登录,provider:', err.provider);
  308. //同步一键登录弹出层隐私协议框是否打勾
  309. let agree = (await uni.getCheckBoxState())[1].state
  310. console.log('agree', agree);
  311. uni.$emit('setAgreementsAgree', agree)
  312. let {
  313. path
  314. } = this.univerifyStyle.buttons.list[res.index]
  315. console.log('path', path);
  316. if (path) {
  317. this.to(path)
  318. } else {
  319. setTimeout(() => {
  320. console.log('agree', this.agree);
  321. this.login_before(err.provider)
  322. }, 500)
  323. }
  324. break;
  325. default:
  326. console.log(err);
  327. break;
  328. }
  329. }
  330. // 以上代码为兼容旧版(HBuilderX3.2.13之前)HBuilderX3.2.13以上版本可直接删除
  331. }
  332. })
  333. },
  334. login(params, type) { //联网验证登录
  335. console.log({
  336. params,
  337. type
  338. });
  339. let action = 'loginBy' + type.trim().toLowerCase().replace(type[0], type[0].toUpperCase())
  340. uniCloud.callFunction({
  341. name: 'uni-id-cf',
  342. data: {
  343. action,
  344. params
  345. },
  346. success: async ({
  347. result
  348. }) => {
  349. console.log("login-result", result);
  350. if (result.code === 0) {
  351. delete result.userInfo.token
  352. // #ifdef MP-WEIXIN
  353. if (type == 'weixin' && !result.userInfo.nickname) {
  354. return this.$refs.userProfile.open(result.uid)
  355. }
  356. // #endif
  357. if (result.type == "register") {
  358. result.userInfo._id = result.uid
  359. }
  360. this.setUserInfo(result.userInfo)
  361. loginSuccess(result)
  362. } else {
  363. uni.showModal({
  364. content: result.msg,
  365. showCancel: false
  366. });
  367. }
  368. },
  369. complete: (e) => {
  370. console.log(e);
  371. if (type == 'univerify') {
  372. uni.closeAuthView()
  373. }
  374. uni.hideLoading()
  375. }
  376. })
  377. },
  378. doUserProfileNext() {
  379. loginSuccess()
  380. },
  381. async getUserInfo(e) {
  382. return new Promise((resolve, reject) => {
  383. uni.getUserInfo({
  384. ...e,
  385. success: (res) => {
  386. resolve(res);
  387. },
  388. fail: (err) => {
  389. uni.showModal({
  390. content: JSON.stringify(err),
  391. showCancel: false
  392. });
  393. reject(err);
  394. }
  395. })
  396. })
  397. }
  398. }
  399. }
  400. </script>
  401. <style lang="scss" scoped>
  402. /* #ifndef APP-NVUE */
  403. view {
  404. display: flex;
  405. box-sizing: border-box;
  406. flex-direction: column;
  407. }
  408. /* #endif */
  409. .quick-login-box {
  410. flex-direction: row;
  411. width: 750rpx;
  412. justify-content: space-around;
  413. position: fixed;
  414. bottom: 10rpx;
  415. left: 0;
  416. }
  417. .item {
  418. flex-direction: column;
  419. justify-content: center;
  420. align-items: center;
  421. height: 200rpx;
  422. }
  423. .logo {
  424. width: 60rpx;
  425. height: 60rpx;
  426. }
  427. .login-title {
  428. margin-top: 4px;
  429. font-size: 26rpx;
  430. }
  431. </style>