wechat.js 3.01 KB
/**
 * 微信model
 * @author: qiujun <jun.qiu@yoho.cn>
 * @date: 15/11/2017
 */

const mysqlCli = global.yoho.utils.mysqlCli;

const TABLE_WECHAT = 'wechat_token';

class WechatModel extends global.yoho.BaseModel {
    constructor(ctx) {
        super(ctx);
    }

    /**
     * 获取微信token与ticket信息,存在并且未过期则返回code=200,
     * 存在且过期返回201,‘update’
     * 不存在返回201,‘save’
     */
    getAccessKeys() {
        let strSql = `select * from ${TABLE_WECHAT} limit 0, 1;`;

        return mysqlCli.query(strSql).then(res => {
            if (res.length > 0) {
                let access_token = res[0].access_token;
                let access_ticket = res[0].access_ticket;
                let expired = new Date(res[0].access_expired).getTime();
                let now = Date.now();

                if (now > expired) { // 过期则去 取新的token与ticket 并且更新数据库
                    return Promise.resolve({
                        code: 201,
                        type: 'update'
                    });
                } else {
                    return Promise.resolve({ // 没过期则直接返回数据库中保存的access_ticket
                        code: 200,
                        access_token,
                        access_ticket
                    });
                }
            } else {
                return Promise.resolve({ // 数据库中没有token数据则新增
                    code: 201,
                    type: 'save'
                });
            }
        });
    }

    /**
     * 保存或者更新微信的token与ticket
     * @param access_token
     * @param access_ticket
     * @param access_create_time
     * @param access_expired
     * @param type 'save'为添加数据 'update'为更新数据
     * @returns {*}
     */
    saveAccessKeys(access_token, access_ticket, access_create_time, access_expired, type) {
        let strSql = '';
        let params = {
            access_token,
            access_ticket,
            access_create_time,
            access_expired
        };

        if (type === 'save') {
            strSql = `insert into ${TABLE_WECHAT}
                    (access_token, access_ticket, access_create_time, access_expired) values
                    (:access_token, :access_ticket, :access_create_time, :access_expired);`;

            return mysqlCli.insert(strSql, params);
        } else if (type === 'update') {
            strSql = `update ${TABLE_WECHAT} set
                      access_token = :access_token,
                      access_ticket = :access_ticket,
                      access_create_time = :access_create_time,
                      access_expired = :access_expired`;

            return mysqlCli.update(strSql, params);
        }

    }

    getIsNeedAddWechatCS(uid) {
        return this.get({
            url: '',
            data: {
                method: 'app.passport.getIsNeedAddWechatCS',
                uid: uid
            }
        });
    }
}

module.exports = WechatModel;