authorizedLoginDialog.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. // componets/authorized-login-dialog/authorizedLoginDialog.js
  2. const defaultAvatarUrl = "../../static/images/no-avatar.png"
  3. const homeApi_empower = "https://aipush.aidsleep.cn";
  4. const token_empower = "b74fd5754c5ef24cf600c39194abdaeb";
  5. Component({
  6. /**
  7. * 组件的属性列表
  8. */
  9. properties: {
  10. showDialog: {
  11. type: Boolean,
  12. value: false,
  13. observer(newVal, oldVal, changePath) {
  14. console.log(newVal, oldVal, changePath)
  15. const that = this;
  16. if (newVal) {
  17. // console.log("开始登录");
  18. // wx.login({
  19. // success: res => {
  20. // if (res.code) {
  21. // // 发送 code 到服务器换取 session_key, openid
  22. // console.log('res.code==' + res.code);
  23. // that.setData({ showLoading: false, wxCode: res.code })
  24. // that.checkHasUserInfo()
  25. // }
  26. // }
  27. // });
  28. that.setData({
  29. avatarUrl: defaultAvatarUrl,
  30. nickName: "",
  31. phoneNumber: "",
  32. disableCommitBtn: true,
  33. showLoading: false,
  34. hasUserInfo: false,
  35. })
  36. } else {
  37. console.log('that.data.wxCode==' + that.data.wxCode);
  38. }
  39. }
  40. }
  41. },
  42. attached() {
  43. },
  44. /**
  45. * 组件的初始数据
  46. */
  47. data: {
  48. intervalId: null,
  49. canIUseGetUserProfile: wx.canIUse('getUserProfile'),
  50. canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  51. avatarUrl: defaultAvatarUrl,
  52. tempAvatarUrl: '',
  53. showLoading: false,
  54. encryptphone: "",
  55. phoneNumber: "",
  56. nickName: "",
  57. disableCommitBtn: true,
  58. hasUserInfo: false,
  59. wxCode: "",
  60. unionid: "",
  61. openid: "",
  62. session_key: "",
  63. latitude: null,
  64. longitude: null,
  65. },
  66. /**
  67. * 组件的方法列表
  68. */
  69. methods: {
  70. // 关闭
  71. onCloseDialog() {
  72. this.setData({ showDialog: false });
  73. },
  74. // 选择头像 后期需要上传
  75. onChooseAvatar(e) {
  76. const { avatarUrl } = e.detail
  77. // this.setData({
  78. // avatarUrl: avatarUrl,
  79. // })
  80. // wx.showToast({ title: "进来了" })
  81. const that = this;
  82. this.setData({ tempAvatarUrl: avatarUrl });
  83. if (avatarUrl.includes("wxfile://")) {
  84. that.uploadAvatar(avatarUrl);
  85. } else {
  86. // 下载头像图片
  87. wx.downloadFile({
  88. url: avatarUrl,
  89. success(res) {
  90. if (res.statusCode === 200) {
  91. console.log('download success');
  92. const tempFilePath = res.tempFilePath
  93. that.uploadAvatar(tempFilePath);
  94. } else {
  95. wx.showToast({ title: '上传失败' })
  96. // wx.showToast({ title: JSON.stringify(res) })
  97. // wx.showToast({ title: JSON.stringify(avatarUrl) })
  98. }
  99. }, fail: function (err) {
  100. wx.showToast({ title: '上传失败' })
  101. // wx.showToast({ title: JSON.stringify(err) })
  102. // wx.showToast({ title: JSON.stringify(avatarUrl) })
  103. }
  104. });
  105. }
  106. this.checkHasUserInfo();
  107. },
  108. uploadAvatar(tempFilePath) {
  109. wx.showLoading({ title: '上传中...' });
  110. const randomString = this.generateRandomString(16);
  111. const base64String = wx.arrayBufferToBase64(new Uint8Array([...randomString].map(c => c.charCodeAt(0))));
  112. wx.request({
  113. url: 'https://aipush.aidsleep.cn/wxuptokens',
  114. method: 'POST',
  115. data: {
  116. rk: base64String
  117. },
  118. success: (res) => {
  119. if (res.data.success) {
  120. this.doUpload(tempFilePath, res.data.token);
  121. } else {
  122. wx.hideLoading();
  123. wx.showToast({ title: '获取上传凭证失败', icon: 'none' });
  124. }
  125. },
  126. fail: () => {
  127. wx.hideLoading();
  128. wx.showToast({ title: '获取上传凭证失败', icon: 'none' });
  129. }
  130. });
  131. },
  132. doUpload(tempFilePath, token) {
  133. wx.uploadFile({
  134. url: 'https://aipush.aidsleep.cn/wxups',
  135. filePath: tempFilePath,
  136. name: 'file',
  137. formData: {
  138. 'token': token
  139. },
  140. success: (res) => {
  141. wx.hideLoading();
  142. const data = JSON.parse(res.data);
  143. if (data.success) {
  144. this.setData({ avatarUrl: data.url });
  145. wx.showToast({ title: '头像上传成功', icon: 'success' });
  146. this.checkHasUserInfo();
  147. } else {
  148. wx.showToast({ title: data.message || '头像上传失败', icon: 'none' });
  149. }
  150. },
  151. fail: () => {
  152. wx.hideLoading();
  153. wx.showToast({ title: '头像上传失败', icon: 'none' });
  154. }
  155. });
  156. },
  157. generateRandomString(length) {
  158. const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  159. let result = '';
  160. for (let i = 0; i < length; i++) {
  161. result += characters.charAt(Math.floor(Math.random() * characters.length));
  162. }
  163. return result;
  164. },
  165. // 输入昵称
  166. onInputNameChange(e) {
  167. console.log('e.detail==' + JSON.stringify(e.detail));
  168. const nickName = e.detail.value
  169. this.setData({
  170. nickName: nickName,
  171. })
  172. wx.setStorageSync('nickName', nickName);
  173. this.checkHasUserInfo();
  174. },
  175. // 输入手机号
  176. onInputPhoneChange(e) {
  177. console.log('e.detail==' + JSON.stringify(e.detail));
  178. const phoneNumber = e.detail.value
  179. this.setData({
  180. phoneNumber: phoneNumber,
  181. })
  182. this.checkHasUserInfo();
  183. },
  184. // 获取手机号
  185. onGetPhoneNumber: function (e) {
  186. console.log('onGetPhoneNumber=' + JSON.stringify(e));
  187. var that = this;
  188. if (e.detail.errMsg === "getPhoneNumber:ok") {
  189. // 发送 encryptedData, iv, 和 sessionKey 到你的后台服务器
  190. wx.request({
  191. url: `${homeApi_empower}/wxtel`,
  192. method: 'POST',
  193. data: {
  194. encryptedData: e.detail.encryptedData,
  195. iv: e.detail.iv,
  196. token: wx.getStorageSync("token") || token_empower,
  197. },
  198. success: function (res) {
  199. // 处理服务器返回的结果
  200. console.log('手机号获取结果:', res.data);
  201. console.log('手机号获取结果:', res.data.encryptphone);
  202. console.log('手机号获取结果:', res.data.shieldphone);
  203. if (!res.data || !res.data.encryptphone || !res.data.shieldphone) {
  204. wx.showToast({
  205. title: '无法获取用户手机号',
  206. icon: 'none'
  207. });
  208. return;
  209. }
  210. console.log('e==' + JSON.stringify(e));
  211. console.log('e.detail==' + JSON.stringify(e.detail));
  212. that.setData({
  213. encryptphone: res.data.encryptphone,
  214. phoneNumber: res.data.shieldphone,
  215. })
  216. that.checkHasUserInfo();
  217. wx.setStorageSync('phoneNumber', res.data.shieldphone);
  218. }
  219. })
  220. }
  221. },
  222. checkHasUserInfo() {
  223. var disableCommitBtn = this.data.avatarUrl == defaultAvatarUrl || !this.data.phoneNumber || !this.data.nickName;
  224. this.setData({
  225. hasUserInfo: this.data.avatarUrl != defaultAvatarUrl && this.data.phoneNumber && this.data.nickName,
  226. disableCommitBtn: disableCommitBtn
  227. })
  228. },
  229. // 提交
  230. handleUserInfo: function (e) {
  231. if (!this.data.hasUserInfo) {
  232. wx.showToast({
  233. title: '请设置头像、昵称和手机号',
  234. icon: 'none'
  235. });
  236. return;
  237. }
  238. var that = this;
  239. that.getLocation(e);
  240. },
  241. getLocation(e) {
  242. const that = this;
  243. wx.getSetting({
  244. success(res) {
  245. if (res.authSetting['scope.userLocation']) {
  246. // 用户已经授权
  247. wx.getLocation({
  248. type: 'gcj02', // 返回可以用于wx.openLocation的经纬度
  249. success(locationRes) {
  250. that.setData({
  251. latitude: locationRes.latitude,
  252. longitude: locationRes.longitude,
  253. error: null
  254. });
  255. console.log('纬度:', locationRes.latitude);
  256. console.log('经度:', locationRes.longitude);
  257. that.authorizedLogin(e);
  258. },
  259. fail(err) {
  260. that.setData({
  261. latitude: null,
  262. longitude: null,
  263. error: err.message
  264. });
  265. console.error('获取位置失败:', err.message);
  266. that.authorizedLogin(e);
  267. }
  268. });
  269. } else {
  270. // 用户未授权
  271. wx.authorize({
  272. scope: 'scope.userLocation',
  273. success() {
  274. // 用户同意授权后再次获取位置
  275. that.getLocation();
  276. },
  277. fail() {
  278. // 用户拒绝授权
  279. that.setData({
  280. latitude: null,
  281. longitude: null,
  282. error: '用户拒绝授权获取地理位置'
  283. });
  284. console.error('用户拒绝授权获取地理位置');
  285. that.authorizedLogin(e);
  286. }
  287. });
  288. }
  289. }
  290. });
  291. },
  292. authorizedLogin(e) {
  293. const that = this;
  294. if (e?.detail?.userInfo) {
  295. // 用户点击允许,获取到用户信息
  296. this.setData({
  297. showLoading: true,
  298. disableCommitBtn: true,
  299. });
  300. console.log("authorizedLogin=>"+{
  301. token: wx.getStorageSync("token") || token_empower,
  302. unionid: wx.getStorageSync("unionid"),
  303. openid: wx.getStorageSync("openid"),
  304. avatarUrl: that.data.avatarUrl,
  305. nickname: that.data.nickName,
  306. encryptphone: that.data.encryptphone,
  307. longandlat: that.data.longitude + "|" + that.data.latitude
  308. });
  309. wx.request({
  310. url: `${homeApi_empower}/wxlogin`,
  311. data: {
  312. token: wx.getStorageSync("token") || token_empower,
  313. unionid: wx.getStorageSync("unionid"),
  314. openid: wx.getStorageSync("openid"),
  315. avatarUrl: that.data.avatarUrl,
  316. nickname: that.data.nickName,
  317. encryptphone: that.data.encryptphone,
  318. longandlat: that.data.longitude + "|" + that.data.latitude
  319. },
  320. method: 'POST',
  321. success: function (loginRes) {
  322. console.log('loginRes=' + JSON.stringify(loginRes));
  323. console.log('loginRes.data=' + JSON.stringify(loginRes.data));
  324. if (loginRes.data.codes && loginRes.data.codes == 'success') {
  325. that.setData({ showLoading: false });
  326. console.log('123123123');
  327. console.log('loginRes.data.back.unionid=' + loginRes.data.back.unionid);
  328. console.log('loginRes.data.back.openid=' + loginRes.data.back.openid);
  329. wx.setStorageSync('unionid', loginRes.data.back.unionid);
  330. wx.setStorageSync('openid', loginRes.data.back.openid);
  331. that.setData({
  332. disableCommitBtn: false,
  333. unionid: loginRes.data.back.unionid,
  334. openid: loginRes.data.back.openid,
  335. });
  336. wx.setStorageSync('userInfo', {
  337. unionid: that.data.unionid,
  338. openid: that.data.openid,
  339. session_key: that.data.session_key,
  340. nickName: that.data.nickName,
  341. avatarUrl: that.data.avatarUrl,
  342. encryptphone: that.data.encryptphone,
  343. phoneNumber: that.data.phoneNumber
  344. })
  345. wx.setStorageSync('hasAuth', true);
  346. that.triggerEvent('authorizationSuccessful', true);
  347. // 获取后台授权
  348. that.startInterval();
  349. } else {
  350. that.setData({ showLoading: false });
  351. wx.showToast({
  352. title: '后台授权失败',
  353. icon: 'none'
  354. });
  355. }
  356. },
  357. fail: function () {
  358. that.setData({ showLoading: false });
  359. wx.showToast({
  360. title: '后台授权失败',
  361. icon: 'none'
  362. });
  363. }
  364. });
  365. } else {
  366. // 用户拒绝授权
  367. wx.showToast({
  368. title: '您拒绝了授权',
  369. icon: 'none'
  370. });
  371. // 可以选择在这里处理用户拒绝授权后的逻辑,如跳转到其他页面或显示提示信息
  372. }
  373. },
  374. // 轮询后台信息 暂时废弃
  375. startInterval: function () {
  376. var that = this;
  377. this.data.intervalId = setInterval(() => {
  378. console.log('后台授权中...');
  379. wx.request({
  380. url: `${homeApi_empower}/wxstatus`,
  381. data: {
  382. unionid: wx.getStorageSync('unionid'),
  383. openid: wx.getStorageSync('openid'),
  384. token: wx.getStorageSync('token') || token_empower,
  385. },
  386. method: 'POST',
  387. success: function (intervalRes) {
  388. that.setData({ showLoading: false });
  389. that.clearInterval();
  390. console.log('intervalRes=' + JSON.stringify(intervalRes));
  391. console.log('intervalRes.data=' + JSON.stringify(intervalRes.data));
  392. if (intervalRes.data && intervalRes.data.st && intervalRes.data.status && intervalRes.data.st == 'success' && intervalRes.data.status == '1') {
  393. wx.setStorageSync('hasHotelAuth', true);
  394. wx.setStorageSync('hotelEmpower', intervalRes.data.hotel);
  395. wx.setStorageSync('roomEmpower', intervalRes.data.room);
  396. } else {
  397. wx.setStorageSync('hasHotelAuth', false);
  398. }
  399. },
  400. fail: function (error) {
  401. that.setData({ showLoading: false });
  402. that.clearInterval();
  403. }
  404. });
  405. }, 3000);
  406. },
  407. clearInterval: function () {
  408. var that = this;
  409. if (this.data.intervalId) {
  410. clearInterval(that.data.intervalId);
  411. that.data.intervalId = null;
  412. }
  413. },
  414. }
  415. })