nodejs 微信小程序登录分享二维码等操作
发布于 1 年前 作者 lwcbest 1226 次浏览 来自 分享

取UnionId和用户信息

const wechatAuthUtil = module.exports;
wechatAuthUtil.getWeChatUserUnionIdPromise = function (paramsObject, encryptedData, iv) {
    if (!paramsObject) {
        commonLogger.error('[getWeChatUserUnionIdPromise] error: no paramsObject.');
    }

    let address = buildAddress(paramsObject);
    
    const handleResult = function (result) {
        commonLogger.info('[handleResult] info: result ', result);
        if (!!result.errcode) {
            commonLogger.error('[getWXOpenId] error: code ', result.errcode, ' errMsg ', result.errmsg);
            let error = result.errmsg;
            throw new Error(error);
        } else {
           if (!!result.unionid && !!result.openid){
               return {unionId:result.unionid, openId:result.openid};
           }else {
               if (!result.openid) {
                  throw new Error('there is no openId in js_code request');
               }
               if (!!result.session_key) {
                  let decodeData = decryptData(result.session_key, encryptedData, iv);
                  commonLogger.debug('[handleResult] decodeData:', decodeData);
                  if (!!decodeData.unionId) {
                    commonLogger.debug('[handleResult] decodeData:', JSON.stringify(decodeData));
                    return {unionId:decodeData.unionId, openId:result.openid};
                  } else {
                    throw new Error('there is no unionId in encryptedData');
                  }
                } else {
                  throw new Error('session_key is not exists');
                }
            }       
        }
    };

    return httpsGetPromise(address)
        .then(handleResult);
};

取openId

wechatAuthUtil.getWeChatOpenIdPromise = function (paramsObject) {
    if (!paramsObject) {
        commonLogger.error('[getWeChatOpenIdPromise] error: no paramsObject.');
    }

    let address = buildAddress(paramsObject);
    
    const handleResult = function (result) {
        commonLogger.info('[handleResult] info: result ', result);
        if (!!result.errcode) {
            commonLogger.error('[getWXOpenId] error: code ', result.errcode, ' errMsg ', result.errmsg);
            let error = new Error(result.errmsg);
            error.code = 3;
            throw error;
        } else {
           if (!!result.openid){
               return {openId:result.openid};
           }else {
               throw new Error('openId is null');    
           }       
        }
    };

    return httpsGetPromise(address)
        .then(handleResult);
};

取token生成二维码

wechatAuthUtil.getWeChatAccessToken = function (paramsObject) {
    if (!paramsObject) {
        commonLogger.error('[getWeChatAccessToken] error: no paramsObject.');
    }

    let address = buildAccessToken(paramsObject);

    const handleResult = function (result) {
        commonLogger.info('[handleResult] info: result ', result);
        if (!!result.errcode) {
            commonLogger.error('[getWXOpenId] error: code ', result.errcode, ' errMsg ', result.errmsg);
            let error = result.errmsg;
            throw new Error(error);
        } else {
           if (!!result.access_token && !!result.expires_in){
               return result;
           }else {
               throw new Error('access_token or expires_in is not exists'); 
           }       
        }
    };

    return httpsGetPromise(address)
        .then(handleResult);
};

利用token生成直接登录的二维码

wechatAuthUtil.getWeChatMiniProgramQRCode = function (accessParams, qrParams, numberId, needReproduce) {
    commonLogger.debug('[getWeChatMiniProgramQRCode] qrParams:', qrParams, ' numberId:', numberId, ' needReproduce:', needReproduce);
    const self = this;
    const path = md5.createWithAlgorithm(numberId.toString(), 'sha256') + '.png';                
    const root = 'gamebox/img';
    let config = {};
    config.host = specialConfig.ftpConfig.host;
    config.user = specialConfig.ftpConfig.user;
    config.password = specialConfig.ftpConfig.password;
    let ftpClient = new ftp();
    let isInclude = false;
    let resultDomain;

    const isQRCodeExist = function () {
        if (!!needReproduce) {
            return new Promise(function (resolve) {
                resolve(false);
            });
        }
        return new Promise(function (resolve, reject) {
            ftpClient.on('ready', function () {
                ftpClient.cwd(root, function (err, currentDir) {
                    ftpClient.list(function (err, list) {
                        if (err) {
                            reject(err);
                        };
                        commonLogger.debug('[getWeChatMiniProgramQRCode][isQRCodeExist] list:', JSON.stringify(list));
                        for (let i = 0; i < list.length; i++) {
                            if (list[i].name === path) {
                                isInclude = true;
                                resultDomain = specialConfig.ftpConfig.domain + '/' + root + '/' + path;
                                resolve(true);
                            }
                        }
                        resolve(false);
                        ftpClient.end();
                    });
                });
            });
          
            ftpClient.connect(config);
        });
    };
    
    const getAccessToken = function (result) {
        if (!result) {
            return self.getWeChatAccessToken(accessParams);
        }
    };

    const getQRCode = function (result) {
        if (!isInclude) {
            commonLogger.debug('[getQRCode] result:', result);
            const qrUrl = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + result.access_token;
            //const qrUrl = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=' + result.access_token;
            return axios({
                method: 'post',
                responseType:'stream',			
                url: qrUrl,
                data: qrParams
              });
        } 
    };

    const handleResult = function (result) {
        if (!isInclude) {
            if (result.status === 200){
                return new Promise(function (resolve, reject) {
                    ftpClient.on('ready', function () {
                        ftpClient.cwd(root, function (err, currentDir) {
                            commonLogger.debug('[getWeChatMiniProgramQRCode] currentDir:', currentDir);
                            ftpClient.put(result.data, path, function (err) {
                                if (err) {
                                    reject(err);
                                };
                                resolve(specialConfig.ftpConfig.domain + '/' + root + '/' + path);
                                ftpClient.end();
                            });
                        });
                    });
                  
                    ftpClient.connect(config);
                });
            }else {
                commonLogger.error('[getWeChatMiniProgramQRCode] error: code ', result.status, ' errMsg: ', result.msg);
                let error = result.msg;
                throw new Error(error);
            }
        } else {
            commonLogger.debug('[getWeChatMiniProgramQRCode][handleResult] resultDomain:', resultDomain);
            return resultDomain;
        }
    };

    return isQRCodeExist()
        .then(getAccessToken)
        .then(getQRCode)
        .then(handleResult);
};
回到顶部