# 获取用户信息

## 1.获取openid

```
// 登录
wx.login({
  success: ({ code }) => {
    // 发送 res.code 到后台换取 openId, sessionKey, unionId
    console.log(code, 'res.code')
    wx.request({
      url: 'https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code',
      data: {
        appid: appid,
        secret: secret,
        js_code: code,
        grant_type: 'authorization_code'
      },
      success: ({ data }) => {
        console.log(data, '小程序的openid')
        this.globalData.openid = data.openid
      }
    })
  }
})
```

## 2.获取用户信息

```
wx.getSetting({
  success: res => {
    if (res.authSetting['scope.userInfo']) {
      // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
      wx.getUserInfo({
        success: res => {
          console.log(res.userInfo, 'res.userInfo')
          // 可以将 res 发送给后台解码出 unionId
          this.globalData.userInfo = res.userInfo
          // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
          // 所以此处加入 callback 以防止这种情况
          if (this.userInfoReadyCallback) {
            this.userInfoReadyCallback(res)
          }
        }
      })
    } else {
      wx.authorize({
        scope: 'scope.userInfo',
        success: () => {
          wx.getUserInfo({
            success: res => {
              console.log(res.userInfo, '弹框确认获取到的用户信息res.userInfo')
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      })
    }
  }
})
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yicoding.gitbook.io/wechat/ke-hu-duan/huo-qu-yong-hu-xin-xi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
