auth.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import {getopenId} from "../requests/api";
  2. async function checkSession(){
  3. return new Promise((resolve, reject) => {
  4. wx.checkSession({
  5. success() {
  6. resolve(true)
  7. },
  8. fail() {
  9. resolve(false)
  10. }
  11. })
  12. })
  13. }
  14. async function authlogin(){
  15. return new Promise((resolve,reject)=>{
  16. wx.login({
  17. success:async function (res) {
  18. // 进行登录操作
  19. resolve(res)
  20. },
  21. fail:function (err){
  22. wx.showToast({
  23. title: '获取code失败',
  24. icon: 'none'
  25. })
  26. reject(err);
  27. }
  28. })
  29. })
  30. }
  31. // 检测登录状态,返回 true / false
  32. async function checkHasLogined() {
  33. const openId = wx.getStorageSync('openId');
  34. if (!openId) {
  35. return false
  36. }
  37. const loggined = await checkSession();
  38. if (!loggined) {
  39. wx.removeStorageSync('openId')
  40. return false
  41. }
  42. return true
  43. }
  44. function wxaCode(){
  45. return new Promise((resolve, reject) => {
  46. wx.login({
  47. success(res) {
  48. return resolve(res.code)
  49. },
  50. fail() {
  51. wx.showToast({
  52. title: '获取code失败',
  53. icon: 'none'
  54. })
  55. return resolve('获取code失败')
  56. }
  57. })
  58. })
  59. }
  60. function getUserInfo() {
  61. return new Promise((resolve, reject) => {
  62. wx.getUserInfo({
  63. success: res => {
  64. resolve(res)
  65. },
  66. fail: err => {
  67. reject(err)
  68. }
  69. })
  70. })
  71. }
  72. // 检查是否位置授权
  73. function getSetting(){
  74. return new Promise(function (resolve, reject) {
  75. wx.getSetting({
  76. success: (res) => {
  77. resolve(res)
  78. },
  79. fail: function fail(error) {
  80. wx.showModal({
  81. title: '网络错误',
  82. content: '网络出错,请刷新重试',
  83. showCancel: false
  84. })
  85. reject(error);
  86. },
  87. })
  88. })
  89. }
  90. // 获取位置信息
  91. function getLocation(){
  92. return new Promise(function (resolve, reject) {
  93. wx.getLocation({
  94. altitude: 'false',
  95. type: 'wgs84',
  96. success: (res) => {
  97. resolve(res)
  98. },
  99. fail: function fail(error) {
  100. wx.showToast({
  101. title: '未定位到您所在位置',
  102. icon: 'none'
  103. })
  104. // Toast.fail('未定位到您所在位置');
  105. // this.setData({
  106. // havePower: {
  107. // result: "fail",
  108. // message: "未定位到您的位置"
  109. // }
  110. // })
  111. reject(error);
  112. },
  113. })
  114. })
  115. }
  116. module.exports = {
  117. checkHasLogined: checkHasLogined,
  118. wxaCode: wxaCode,
  119. getUserInfo: getUserInfo,
  120. authlogin: authlogin,
  121. getSetting,
  122. getLocation,
  123. }