zoukankan      html  css  js  c++  java
  • 微信access_token和jsapi_ticket的存储

    var MongodbClient = require('mongodb').MongoClient;
    var DB_CONN_STR = 'mongodb://binf:FashionBinfabc123@10.168.48.227:27017/binf';
    var request = require('request');
    var express = require('express');
    var session = require('express-session');
    var sha1 = require('sha1');
    var config = {
        "AppID": "wx38e76585e4db25a4",
        "AppSecret": "f8f2074cbc63b8bb2bfffcd87865ba1e",
    };
    
    var wx = {
        // accessToken的获取和更新
        'getAccessToken': function getAccessToken(callback) {
            MongodbClient.connect(DB_CONN_STR, function(err, db) {
                // console.log("mongodb连接成功");
                var collection = db.collection('accessToken');
                collection.find().toArray(function(err, result) {
                    if (err) {
                        console.log("Error:" + err);
                        return;
                    }
                    if (result.length != 0) {
                        // console.log('数据库存在token')
                        // console.log("accessToken:==" + result);
                        var time = result[0].expires_in - (new Date().getTime() - result[0].timestamp) / 1000
                            // var time = 30 - (new Date().getTime() - result[0].timestamp) / 1000;
                            // console.log('time=' + time);
                        if (time > 0) {
                            session.tokenDate = result[0];
                            callback();
                        } else {
                            console.log('数据库accessToken已过期');
                            wx.updateAccessToken(collection, result, callback);
                        }
                    } else {
                        // console.log('数据库中没有token')
                        wx.requestAccessToken(collection, callback);
                    }
                });
            });
        },
        'requestAccessToken': function requestAccessToken(collection, callback) {
            var obj = {
                "url": "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + config.AppID + "&secret=" + config.AppSecret,
                "json": true
            };
            request(obj, function(err, res, body) {
                console.log("url获取数据accesstoken:" + JSON.stringify(body));
                body = JSON.parse(body);
                body.timestamp = new Date().getTime();
                collection.insert(body, function(err, result) {
                    if(err){
                        console.log("插入数据报错:"+err)
                        return;
                    }
                    console.log("数据库token插入成功" + result);
                    session.tokenDate = body;
                    callback();
                });
            });
        },
        'updateAccessToken': function updateAccessToken(collection, data, callback) {
            var where = { "_id": data[0]._id };
            var obj = {
                "url": "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + config.AppID + "&secret=" + config.AppSecret,
                "json": true
            };
            request(obj, function(err, res, body) {
                body = JSON.parse(body);
                var updateStr = { $set: body };
                body.timestamp = new Date().getTime();
                body._id = where._id;
                console.log('url获取的accessToken:===' + JSON.stringify(body));
                collection.update(where, updateStr, function(err, result) {
                    console.log("数据库accesstToken更新成功" + result);
                    session.tokenDate = body;
                    callback();
                });
            });
        },
        'getJsapiTicket': function getJsapiTicket(callback) {
            MongodbClient.connect(DB_CONN_STR, function(err, db) {
                var collection = db.collection('jsapiTicket');
                collection.find().toArray(function(err, result) {
                    if (result.length != '') {
                        console.log('数据库中存在jsapiTicket'+JSON.stringify(result));
                        var time = result[0].expires_in - (new Date().getTime() - result[0].timestamp) / 1000;
                        // var time = 30 - (new Date().getTime() - result[0].timestamp) / 1000;
                        console.log("jsapi---time---==" + time);
                        if (time > 0) {
                            session.jsapiTicket = result[0];
                            callback();
                        } else {
                            console.log("jsapiTicket过期");
                            wx.updateJsapiTicket(collection, result, callback);
                        }
                    } else {
                        console.log('数据库中不存在jsapiTicket');
                        wx.requestJsapiTicket(collection, callback);
                    }
                });
            });
        },
        'requestJsapiTicket': function requestJsapiTicket(collection, callback) {
            wx.getAccessToken(function() {
                console.log("access_token:===" + session.tokenDate.access_token);
                var obj = {
                    'url': 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + session.tokenDate.access_token + '&type=jsapi',
                    'json': true
                };
                request(obj, function(err, res, body) {
                    body = JSON.parse(body);
                    body.timestamp = new Date().getTime();
                    console.log("url获取jsticket:" + JSON.stringify(body));
                    collection.insert(body, function(err, result) {
                        if(err){
                            console.log(err)
                        }
                        console.log("jsapiTicket插入数据库成功:" + result);
                        session.jsapiTicket = body;
                        callback();
                    });
                });
            });
        },
        'updateJsapiTicket': function updateJsapiTicket(collection, data, callback) {
            wx.getAccessToken(function() {
                var where = { "_id": data[0]._id };
                // console.log(data[0]._id);
                console.log("获取jsapiTicket的access_token:===" + session.tokenDate.access_token);
                var obj = {
                    "url": 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + session.tokenDate.access_token + '&type=jsapi',
                    "json": true
                };
                request(obj, function(err, res, body) {
                    body = JSON.parse(body);
                    var updateStr = { $set: body };
                    body.timestamp = new Date().getTime();
                    // accessToken没过期获取的jsapiTicket是一样的
                    console.log('url获取的jsapiTicket:===' + JSON.stringify(body));
                    collection.update(where, updateStr, function(err, result) {
                        console.log("数据库jsapiTicket更新成功" + result);
                        session.jsapiTicket = body;
                        callback();
                    });
                });
            });
        },
        'getSignature': function getSignature(requestUrl, res) {
            //requestUrl由前端传递
            wx.getJsapiTicket(function() {
                var timestamp = new Date().getTime(),
                    jsapiTicket = session.jsapiTicket.ticket,
                    noncestr = sha1(timestamp),
                    url = requestUrl;
                console.log('timestamp=' + timestamp + 'jsapiticket=' + jsapiTicket + 'noncestr=' + noncestr + 'url=' + url);
                var signature = sha1('jsapi_ticket=' + jsapiTicket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url);
                console.log(signature);
                res.json({
                    "appid": config.AppID,
                    'timestamp': timestamp,
                    "nonceStr": noncestr,
                    "signature": signature
                });
            });
        }
    };
    
    module.exports = wx;
  • 相关阅读:
    PossibleOrders TopCoder
    505C Mr. Kitayuta, the Treasure Hunter
    p2257 YY的GCD
    浅谈莫比乌斯反演
    Hive基础(3)---Fetch Task(转)
    Hive基础(2)---(启动HiveServer2)Hive严格模式
    mysql 命令行参数
    Hive基础(1)---Hive是什么
    mybatis运行时错误Illegal argument exception argument type mismatch
    【TOMCAT启动异常】The BASEDIR environment variable is not defined correctly
  • 原文地址:https://www.cnblogs.com/maoriaty/p/7807154.html
Copyright © 2011-2022 走看看