WxAuthor.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. const getReq = require('../config.js').getReq
  2. const api = require('../config.js').host
  3. export default class WxAuthor {
  4. constructor(app) {
  5. this.target = app
  6. this.init()
  7. }
  8. // 首先wx.login
  9. init() {
  10. wx.login({
  11. success: res => {
  12. this.ministart(res.code)
  13. }
  14. })
  15. }
  16. // 拿到code 请求act=login op=ministart
  17. ministart(code) {
  18. let params = {
  19. act: "login",
  20. op: "ministart",
  21. code
  22. }
  23. getReq(params, res => {
  24. let { openid, unionid } = res.datas
  25. this.setId(openid, unionid)
  26. // 获取用户授权设置信息
  27. this.getSetting()
  28. })
  29. }
  30. getSetting() {
  31. wx.getSetting({
  32. success: res => {
  33. if (res.authSetting['scope.userInfo']) {
  34. this.getUserInfo()
  35. }
  36. else {
  37. return
  38. }
  39. }
  40. })
  41. }
  42. getUserInfo() {
  43. wx.getUserInfo({
  44. success: res => {
  45. this.setUserInfo(res.userInfo, res.userInfo.nickName)
  46. let userInfo = Object.assign({}, this.target.globalData.userId, this.target.globalData.userInfo)
  47. this.wxauthen(userInfo)
  48. }
  49. })
  50. }
  51. wxauthen(userInfo) {
  52. let params = {
  53. user_info: userInfo,
  54. act: "login",
  55. op: "wxauthen"
  56. }
  57. getReq(params, res => {
  58. wx.setStorageSync('session_id', res.datas.HPHPSESSID)
  59. if (res.code == 200) {
  60. let url = this.getUrl()
  61. wx.reLaunch({
  62. url
  63. })
  64. }
  65. else {
  66. wx.showToast({
  67. icon: 'none',
  68. title: '登陆失败',
  69. duration: 2000
  70. })
  71. }
  72. })
  73. }
  74. getUrl() {
  75. let len = getCurrentPages().length
  76. let currentPage = getCurrentPages()[len - 1]
  77. let params = ''
  78. if (currentPage.options) {
  79. for (let k in currentPage.options) {
  80. params = params + k + '=' + currentPage.options[k] + '&'
  81. }
  82. params = params.slice(0, params.length - 1)
  83. }
  84. let current_url = "/" + currentPage['route']
  85. if (params) {
  86. current_url = current_url + '?' + params
  87. }
  88. return current_url
  89. }
  90. // 设置用户信息
  91. setUserInfo(userInfo, nickName) {
  92. this.target.globalData.userInfo = userInfo
  93. this.target.globalData.userInfo.nickname = nickName
  94. }
  95. //设置openid, unionid
  96. setId(openid, unionid) {
  97. this.target.globalData.userId.openid = openid
  98. this.target.globalData.userId.unionid = unionid
  99. }
  100. }