promise2.js 6.17 KB
/**
 * Created by shipfi on 2016/11/19.
 */

const path = require('path');
var jsuri = require('jsuri');
var fetch = require('node-fetch');
var fs = require('fs');
var json2csv = require('json2csv');

var csvFields = ['subscribe','openid','nickname','sex','city','province','country','headimgurl','subscribe_time','remark','groupid'];

//var accessToken = '2Y3cDvNzN2UNqEKXXGrnQox3Iv_DssZIlhrYOY5pAy_ZFhm1EkLyiJ68gq1DirrbpMv-YVVuo4P1BH9AMEE2w9C1Bhunj5F0Oj1If6qq0lwo58HZYqUNPyzcFgBN95aJTAGiALDBIO';
var accessToken = 'IX6Bajo9XVnVX02JzImWeQOEEtNohoZB-5EWSDUxYpsDPwZdBOMyzK0S0ruuYwgfW6XObv0VLlruKmnp5k6wwRV_QeAEbVLoBWlRQKp9CUteKkJLwbxob0NMuZc7JqlCSTLfAIDABT';

var getOpenIdFromWx = function(openid=null) {
    var wxGetUsersURL = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='+accessToken;
    if(openid) {
        wxGetUsersURL = wxGetUsersURL+"&next_openid="+openid;
    }
    //console.log(wxGetUsersURL);
    return new Promise(function(resolve,reject){
        fetch(wxGetUsersURL).then(function(res){
            resolve(res.json());
        }).catch(function(err){
            reject(err);
        });
    });
};

var getWxUsersInfo = function(openids,file_id=0){
    return new Promise(function(resolve,reject){
        if(!openids) reject(0);
        var lengths = openids.length;
        if(lengths<=0) reject(0);
        var times = parseInt(lengths/100)+1;
        var wxUserInfoUrl = 'https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token='+accessToken;

        var lastOpenId = openids[lengths-1];
        // var jsonStream = { 'user_list':[] };

        
        for(var i=0;i<times;i++) {
            var iBegin = 0;
            var iEnd = 99;

            if(openids.length<0)
                return;
            
            var tmpOpenIds = openids.splice(iBegin,iEnd);
            var tmpJsonStream = { 'user_list':[] };
            tmpJsonStream.user_list = tmpOpenIds.map(function(x){
                return {"openid":x,"lang":'zh-CN'}
            });
            var userListLength = tmpJsonStream.user_list.length;
            var stringJsonStream = JSON.stringify(tmpJsonStream);
            // jsonStream.user_list = openids.splice(iBegin,iEnd).map(function(x){
            //             return {"openid":x,"lang":'zh-CN'}
            // });

            if(userListLength>0) {
                fetch(wxUserInfoUrl,{method:'POST',body:stringJsonStream}).then(function(res){
                    return res.json();
                }).then(function(json){
                    console.log('Begin:========================================================>'+iBegin);
                    var result = json2csv({data:json.user_info_list,fields:csvFields,'hasCSVColumnTitle':false});
                    console.log(result);
                    var fileName = path.join(process.cwd(),'/data_'+file_id+'.csv');
                    fs.appendFile(fileName,"\n",'utf8',function(err){
                        if(err) throw err;
                    });
                    fs.appendFile(fileName,result,'utf8',function(err){
                        if(err) throw err;
                        console.log('Saved.');
                    });
                    
                    if(i>=times-1) {
                        resolve(lastOpenId);
                    }
                    console.log('End:========================================================>'+iEnd);
                }).catch(function(err){
                    reject(0);
                });
            }
        }
    });
   
    

    
   
   
    // for(var i=0;i<times;i++) {
    //     jsonStream.user_list = [];
    //     var iBegin = i*100;
    //     var iEnd = (i*100+99)>(lengths-1)?(lengths-1):i*100+99;
    //     if(iBegin>iEnd) break;
    //     console.log(iBegin+':========================================================>'+iEnd);
    //     jsonStream.user_list = openids.splice(iBegin,iEnd).map(function(x){
    //         return {"openid":x,"lang":'zh-CN'}
    //     });
    //
    //     if(jsonStream.user_list.length>0) {
    //         fetch(wxUserInfoUrl,{method:'POST',body:JSON.stringify(jsonStream)}).then(function(res){
    //             return res.json()
    //         }).then(function(json){
    //             console.log(JSON.stringify(json.user_info_list));
    //             // var result = json2csv({data:json.user_info_list,fields:csvFields});
    //             // //console.log(result);
    //             //  var fileName = path.join(process.cwd(),'/data_'+file_id+'.csv');
    //             //  fs.appendFile(fileName,result,'utf8',function(err){
    //             //      if(err) throw err;
    //             //      console.log('Saved.');
    //             //  });
    //         });
    //
    //     }
    // }
};

var processDatas = function(_nextOpenid=null) {
    var openidArrays = [];
    var goFetch = function(nextOpenId,fileIndex=0) {
        return getOpenIdFromWx(nextOpenId).then(function(json){
            //console.log(response);
            if(typeof json.data != 'undefined') {
                var openids = json.data.openid;
                openidArrays = openidArrays.concat(openids);
                var openidLength = openids.length;
                var lastOpenId = openidLength?openids[openidLength-1]:null;

                //console.log(fileIndex+'++++++++++++++++++++++++++++++++++++++++++++++++++++>'+openidLength);
                //console.log(openids);
                //getWxUsersInfo(openids,fileIndex);
                getWxUsersInfo(openids).then(function(theRetLastOpenId){
                    goFetch(theRetLastOpenId,fileIndex++); 
                },function(rejRes){
                    Promise.resolve(rejRes);
                });
                // if(lastOpenId) {
                //    
                // }else{
                //     Promise.resolve(openidArrays);
                // }
            }else{
                Promise.resolve(openidArrays);
            }
        }).catch(function(err){
           Promise.reject(err); 
        });
    }

    return goFetch(_nextOpenid);
};

// var xxx = [];
// for(var i=0;i<298;i++) {
//     xxx.push('OOOOPPPPP'+i);
// }
// getWxUsersInfo(xxx);
var _nextOpenid = null;
 processDatas(_nextOpenid).then(function(data){
     //console.log(data);
});
//console.log(openIds);