Wechat applet development practice 6_2 Obtain user information

6.6 Get user information

If the developer needs to obtain the user's personal information (avatar, nickname, gender, and region), he can call the wx.getUserProfile interface to obtain it. The wx.getUserProfile interface can only be called in the page click event (for example, in the callback of bindtap on the button). Every time it is called, an authorization window will pop up, and userInfo will be returned after the user agrees. The code for obtaining user information through the wx.getUserProfile interface is as follows:
WXML file: user_info.wxml

<view class="container">
  <view class="userinfo">
    <block wx:if="{
     
     {!hasUserInfo}}">
      <button bindtap="getUserProfile">获取头像昵称</button>
    </block>
    <block wx:else>
      <image class="userinfo-avatar" src="{
     
     {userInfo.avatarUrl}}" mode="cover"></image>
      <text>{
   
   {userInfo.nickName}}</text>
    </block>
  </view>
</view>

The getUserProfile function in the user_info.js file is the event handler function of the button button, and wx.getUserProfile is called in this function:

Page({
    
    
  data: {
    
    
    userInfo: {
    
    },
    hasUserInfo: false,
  },
  getUserProfile(e) {
    
    
    wx.getUserProfile({
    
    
      desc: '获取用户信息', 
      success: (res) => {
    
    
        console.log(res)
        this.setData({
    
    
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  }
})

The structure of the data returned after wx.getUserProfile is called successfully is as follows:

  • userInfo: user information object
  • rawData: the raw data string excluding sensitive information, used to calculate the signature
  • signature: Use sha1( rawData + sessionkey ) to get a string for verifying user information, see signature verification and encryption and decryption of user data for details
  • encryptedData: encrypted data of complete user information including sensitive data, see signature verification and encryption and decryption of user data for details
  • iv: the initial vector of the encryption algorithm, see signature verification and encryption and decryption of user data for details
  • cloudID: The cloud ID corresponding to the sensitive data, which will be returned only after the cloud-developed applet is activated, and the open data can be directly obtained through the cloud call. For details, see Directly obtain the open data through the cloud call, where userInfo is the user information object, and the following code executes wx
    . After the getUserProfile call is successful, the userInfo information in the data is returned:
	avatarUrl: "https://thirdwx.qlogo.cn/mmopen/......."
	city: "xxxxxx"
	country: "China"
	gender: 1
	language: "zh_CN"
	nickName: "xxxxxx"
	province: "xxxxxx"

If the developer needs to display the user's avatar and nickname information in the interface, the user information can also be displayed through the component. This component does not require user confirmation, and the user information can be directly displayed in the interface:

<view class="container">
  <view class="userinfo">
    <view class="userinfo-avatar" bindtap="bindViewTap">
      <open-data type="userAvatarUrl"></open-data>
    </view>
    <open-data type="userNickName"></open-data>
  </view>
</view>

6.7 Get the user's mobile phone number

The user's mobile phone number is important user privacy data. The purpose of obtaining the user's mobile phone number in the app is to facilitate contact with the user, such as sending order information SMS to the user through the mobile phone number. The WeChat applet provides a specific button component (the open-type value of the button is getPhoneNumber) to obtain the phone number. After the user clicks and agrees, the encrypted data returned by the WeChat server can be obtained through the bindgetphonenumber event processing function. To obtain the final mobile phone number, it is necessary to call the business server to decrypt the encrypted data. The business server combines session_key and app_id to decrypt the encrypted data and obtain the mobile phone number.
Since the mobile phone number is relatively important user privacy data, there are certain restrictions on obtaining the mobile phone number:
1) To obtain the mobile phone number bound to a WeChat user, the wx.login interface must be called first.
2) Because the mobile phone number acquisition interface needs to be triggered actively by the user, the mobile phone number cannot be obtained through the API method, and the acquisition needs to be triggered by clicking the button component.
3) At present, this interface is open to non-individual developers and mini programs that have completed certification (excluding overseas entities).
Code sample: user_mobile.wxml

<scroll-view scroll-y="true">
  <div style="display:flex;padding:10rpx">
    <div>您的手机号码:</div>  
    <div style="flex-grow:1">{
   
   {mobile}}</div>
  </div>
  <div style="display:flex;padding:10rpx">
    <button style="width:100%" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号码</button>
  </div>
</scroll-view>

Code sample: user_mobile.js

function aesDecode(page, data, iv) {
    
    
  var domain = getApp().globalData.domain;
  var url = domain + '/aes_decode';
  var ssid = getApp().globalData.ssid
  wx.request({
    
    
    url: url,
    data: {
    
    
      ssid: ssid,
      data: data,
      iv: iv
    },
    success: function (res) {
    
    
      if (res.statusCode === 200) {
    
    
        page.setData({
    
    
          mobile: res.data.phoneNumber
        });
      }
    }
  });
}
Page({
    
    
  data: {
    
    
    mobile: ""
  },
  onLoad: function (options) {
    
    
    var ssdata = getApp().getLogInfo();
    if(ssdata.length < 1){
    
    
      getApp().wxLogin();
    }
  },
  getPhoneNumber: function (e) {
    
    
    var res = e.detail;
    aesDecode(this, res.encryptedData, res.iv);
  }
})

In user_mobile.js, first judge the user's login status in the onLoad event processing function, if not logged in, you need to log in to WeChat first. getPhoneNumber is the event processing function of the bindgetphonenumber event, and the data structure of the parameters of the bindgetphonenumber event processing function is:

  • encryptedData: Encrypted data of complete user information including sensitive data, see Encrypted Data Decryption Algorithm for details
  • iv: Initial vector of the encryption algorithm, see Encrypted Data Decryption Algorithm for details
  • cloudID: The cloud ID corresponding to the sensitive data, which will be returned only after opening the cloud-developed applet. You can directly obtain open data through cloud calls. For details, see Cloud calls to directly obtain open data. When calling the business server to decrypt data, send iv and encryptedData to the
    business Server, business server uses session_key to decrypt encryptedData, the following code is an example of decrypted data:
{
    
    
  "phoneNumber": "13580006666",
  "purePhoneNumber": "13580006666",
  "countryCode": "86",
  "watermark":
  {
    
    
      "appid":"APPID",
      "timestamp": TIMESTAMP
  }
}

Decryption of WeChat Open Data

The Mini Program can obtain the open data provided by WeChat through various front-end interfaces, such as the wx.getUserProfile interface to obtain the user's personal information (avatar, nickname, gender and region). If developers need to obtain sensitive data, they need to symmetrically decrypt the encrypted data (encryptedData) returned by the interface. The decryption algorithm is as follows:
1) The algorithm used for symmetric decryption is AES-128-CBC, and the data is filled with PKCS#7.
2) The target ciphertext for symmetric decryption is Base64_Decode(encryptedData).
3) Symmetric decryption key aeskey = Base64_Decode(session_key).
4) The initial vector of the symmetric decryption algorithm is Base64_Decode(iv), where iv is returned by the data interface.
The following code is the related function of WeChat open data decryption:

//解除KCS#7填充
func PKCS7UnPadding(origData []byte) []byte {
    
    
   length := len(origData)
   unpadding := int(origData[length-1])
   return origData[:(length - unpadding)]
}
//AES-128-CBC解密
func AesCBCDncrypt(encryptData, key, iv []byte) ([]byte, error) {
    
    
   block, err := aes.NewCipher(key)
   if err != nil {
    
    
      panic(err)
   }
   blockSize := block.BlockSize()
   if len(encryptData) < blockSize {
    
    
      panic("ciphertext too short")
   }
   if len(encryptData)%blockSize != 0 {
    
    
      panic("ciphertext is not a multiple of the block size")
   }
   mode := cipher.NewCBCDecrypter(block, iv)
   mode.CryptBlocks(encryptData, encryptData)
   encryptData = PKCS7UnPadding(encryptData)
   return encryptData, nil
}
//微信开放数据解密
func WxDncrypt(rawData, key, iv string) (string, error) {
    
    
   data, err := base64.StdEncoding.DecodeString(rawData)
   if err != nil {
    
    
      return "", err
   }
   key_b, err := base64.StdEncoding.DecodeString(key)
   if err != nil {
    
    
      return "", err
   }
   iv_b, err := base64.StdEncoding.DecodeString(iv)
   if err != nil {
    
    
      return "", err
   }
   dnData, err := AesCBCDncrypt(data, key_b, iv_b)
   if err != nil {
    
    
      return "", err
   }
   return string(dnData), nil
}

Guess you like

Origin blog.csdn.net/gz_hm/article/details/127116859
Recommended