token.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import {
  2. Config
  3. } from './config.js'
  4. class Token {
  5. constructor() {
  6. this.loginUrl = Config.restUrl + '/wx/login';
  7. this.verifyUrl = Config.restUrl + '/wx/verifyToken'
  8. this.verifyLoginUrl = Config.restUrl + '/wx/isRegister'
  9. }
  10. verify(){
  11. var token = wx.getStorageInfoSync('token')
  12. if(!token){
  13. this.getTokenFromServer();
  14. }else{
  15. this._verifyFromServer(token)
  16. }
  17. }
  18. //携带令牌判断令牌是否正确
  19. _verifyFromServer(token){
  20. var that = this;
  21. wx.request({
  22. url: that.verifyUrl,
  23. method:'GET',
  24. data: {
  25. token:token
  26. },
  27. success:function(res){
  28. console.log(res)
  29. var valid = true;
  30. if(!valid){
  31. that.getTokenFromServer();
  32. }
  33. }
  34. })
  35. }
  36. async getTest(){
  37. await wxLogin();
  38. }
  39. wxLogin(){
  40. uni.login({
  41. success (res) {
  42. console.log(res)
  43. }
  44. })
  45. 
  46. }
  47. getTokenFromServer() {
  48. console.log("进入登陆")
  49. //只有根据appid和对应的code才能拿到token
  50. var that = this
  51. uni.login({
  52. success: function(res) {
  53. console.log("登陆成功")
  54. uni.request({
  55. url: that.loginUrl,
  56. method:'GET',
  57. data: {
  58. code: res.code,
  59. appId: uni.getAccountInfoSync().miniProgram.appId
  60. },
  61. success: (res) => {
  62. console.log(1111)
  63. console.log(res)
  64. if(res.data.code == 200){
  65. //判断用户是否注册
  66. uni.request({
  67. url:that.verifyLoginUrl,
  68. method:'GET',
  69. data:{
  70. openid:res.data.data.openid
  71. },
  72. success:(ress) => {
  73. if(!ress.data){
  74. }
  75. }
  76. })
  77. //拿到openid和token存储到服务端
  78. console.log("开始存储")
  79. uni.setStorageSync("token",res.data.data.token)
  80. uni.setStorageSync("openid",res.data.data.openid)
  81. uni.setStorageSync("sessionKey",res.data.data.sessionKey)
  82. console.log("结束存储")
  83. }
  84. }
  85. })
  86. }
  87. })
  88. }
  89. }
  90. export {
  91. Token
  92. }