简体   繁体   中英

How to get a user's wechat open id from a web app?

I have a reservations web app and we are thinking of sending a message to the user via wechat after he makes a reservation.

I looked around the wechat documentation and see that we will need the user's openid but I have no clue how to obtain this.

Do I have to program a "login via wechat" button?

需要获取微信公众号获取用户open id,请到https://open.weixin.qq.com/

Here is one the method we can use to get the openId on login.

Steps :

  • 1- We log the user with wx.login .
  • 2- We get the userInfo with `wx.getUserInfo.
  • 3- In parallel we get the openId
    • To get the openId: We make a GET request to : https://api.weixin.qq.com/sns/jscode2session? on our server.
    • For security purposes, wechat doesn't allow us to make a GET request to their api on the client.
    // Client-side
    /**
     * @description Handle the login to wechat
     * https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html
     * @returns {Promise} Return the user's wechat information.
     * {"openId", "nickName","gender", "city", "province", "country", "avatarUrl" }
     */
    export function handleWxLogin() {
      return new Promise((resolve, reject) => {
         wx.login({
            success : async function (res) {
              const js_code = res.code;
              const userInfo =  getUserInfo()
              const openID = getOpenID(js_code)
              const payload = {
                ...await userInfo,
                ...{openID:await openID}
              }
              console.info('handleWxLogin payload:', payload);
              resolve(payload)
            },
            fail: function(err){
              console.log('wx.login error:',err);
              reject(err)
               }
            })
        })
    }
    /**
     * @description GET request to get the OpenID from the server.
     * @param {String} js_code
     * @returns {Promise} Return openID
     */
    async function getOpenID(js_code){
      // A GET request to our back-end.
     return http.get(`wxUnionID?js_code=${js_code}`).then(res => {
        if(res){
          return res.data.openid;
        }
      }).catch(err => {
        console.warn('getOpenID error:',err,);
      })
    }
    
    /**
     * @description Get the userInfo with wx.getUserInfo
     * https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html
     * @returns {Promise} returns an object
     */
    function getUserInfo(){
      return new Promise((resolve, reject) => {
        wx.getUserInfo({
          success: async function(res) {
            const userInfo = res.userInfo;
            resolve(userInfo)
          },
          fail: function(err){
            console.warn('getUserInfo error:',err,);
            reject('getUserInfo error:',err)
          }
        })
      })
    }

On the Server Side :

  • To get the openId we need:
    • js_code : Code provided during the login
    • apiid and secret : can be found on the developer dashboard

    const bent = require("bent");
    /**
     * @description We get the openid from weixin.
     * https://developers.weixin.qq.com/miniprogram/en/dev/api-backend/open-api/login/auth.code2Session.html
     * @param {String} js_code (the code provided during the login)
     * APP_ID and APP_SECRET can be found on the developper dashboard.
     * @returns {Promise} {session_key, openid}
     */
    module.exports = {
      wxUnionID: async ctx => {
        const query = ctx.request.query;
        const js_code = query.js_code;
        const getJSON = bent("json");
        const user = await getJSON(
          `https://api.weixin.qq.com/sns/jscode2session?appid=${process.env.APP_ID}&secret=${process.env.APP_SECRET}&js_code=${js_code}`
        );
        console.info('user:', user)
        if(user.openid){
          ctx.send({
            statusCode: 200,
            error: null,
            data:user,
          });
        }else{
          ctx.send({
            statusCode: 400,
            error: user,
            data:null,
          });
        }
      }
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM