ServiceController.js 2.91 KB
/**
 * 内部服务,禁止外部访问
 */
if (!sails.config.custom) {
    throw new Error('token not config');
}
var https = require('https');
var url = require('url');
var fs = require('fs');


var custom = sails.config.custom;
module.exports = {
    /**
     * 模板消息发送
     * 1、检测用户是否在数据中
     * 2、使用 template_id_short 获取模板ID
     * 3、发送消息
     * 
     * @api {post} /service/msg 发送微信模板消息
     * @apiName 发送微信模板
     * @apiGroup service
     * 
     * @apiParam {json} data 消息体数据 
     * @apiParam {string} touser 用户ID
     * @apiParam {string} templateId  后台设置的模板ID
     * @apiParam {string} url 消息跳转链接
     * 
     * @apiParamExample {form-data} 请求示例
        data={
                "productType": {
                "value": "商品名称:",
                "color": "#333333"
                },
                "name": {
                "value": "商品名称:",
                "color": "#333333"
                },
                "time": {
                "value": "商品名称:",
                "color": "#333333"
                },
                "remark": {
                "value": "备注:",
                "color": "#333333"
                }
            }
       touser=18913
       templateId:S5TkyGdQeJHongw1lOiJX2aNEJbJrHTyCKJTZDehBT0
       url:http://nong12.com

     *  @apiSampleRequest /service/msg
     */
    msg: function(req, res, next) {
        try{
            var data = JSON.parse(req.body.data);
        }catch(e){
            return res.json({errcode:"-1001",errmsg:"invaild json"});
        }

        var touser = req.body.touser;
        var templateId = req.body.templateId;
        var url = req.body.url;

        // 查询用户
        User.findOne({
            user_id: touser
        }).exec(function(err, row) {
            if (err) {
                return res.json(err);
            }
            if (!row) {
                return res.json({
                    errcode: "-1002",
                    errmsg: "no found user info"
                });
            }
            touser = row.open_id;

            sails.wechat_api.sendTemplate(touser, templateId, url, "#333333", data, function(err, return_data) {
                if (err) {
                    return res.json({errcode:err.code,errmsg:err.name});
                }
                return res.json(return_data);
            });
        });
    },

    /**
     * 获取token
     * @api {get} /service/accessToken 获取token
     * @apiName 获取token
     * @apiGroup service
     * 
     *  @apiSampleRequest /service/accessToken
     */
    accessToken:function(req,res,next){
        sails.wechat_api.getLatestToken(function(err,token){
            if(err){
                return res.json({errcode:err.code,errmsg:err.name});
            }
            token.code = 0;
            return res.json(token);
        });
    }
};