微信回复图文消息
微信回复图文消息
Wenchster 发表于2年前
微信回复图文消息
  • 发表于 2年前
  • 阅读 5
  • 收藏 0
  • 点赞 1
  • 评论 0

腾讯云 新注册用户 域名抢购1元起>>>   

摘要: 跟着别人的博客一步一步操作,刚接触微信端
@RestResource(urlMapping='/WeChatRest/*')
global with sharing class WeChatRestController{
    @HttpGet
    global static void doGet(){
        String signature = RestContext.request.params.get('signature');
        String timestamp = RestContext.request.params.get('timestamp');
        String nonce = RestContext.request.params.get('nonce');
        String echostr = RestContext.request.params.get('echostr');
        System.debug('dean----->'+ echostr + ' - ' + timestamp);
        RestContext.response.addHeader('Content-Type', 'text/plain');
        RestContext.response.responseBody = Blob.valueOf(echostr);
        //此处是直接将echostr返回,使得微信端的验证通过,真正的方法参考微信文档
    }
    
    
    //返回当前时间
    @HttpPost
    global static void doPost(){
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        string strMsg = req.requestBody.toString();  
        XmlStreamReader reader = new XmlStreamReader(strMsg);
        String toUserName = '';
        String fromUserName = '';
        String msgType = '';
        String picURL = '';
        String mediaID = '';
        String locationX = '';
        String locationY = '';
        String URL = '';
        String content = '';
        String msgID = '';
        String event = '';
        String eventKey = '';
        String recognition = '';
        //解析XML
        while(reader.hasNext()){
            if(reader.getLocalName() == 'ToUserName'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    toUserName = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'FromUserName'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    fromUserName = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'MsgType'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    msgType = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'PicURL'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    picURL = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'MediaId'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    mediaID = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'Location_X'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    locationX = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'Location_Y'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    locationY = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'Url'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    URL = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'MsgId'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    msgID = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'Content'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    content = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'Event'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    event = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'EventKey'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    eventKey = reader.getText();
                }
            }
            else if(reader.getLocalName() == 'Recognition'){
                reader.next();
                if(String.isNotBlank(reader.getText())){
                    recognition = reader.getText();
                }
            }
            reader.next();
        }
        //用内部类IncomingMsg来存储
        IncomingMsg inMsg = new IncomingMsg(toUserName, fromUserName, msgType, picURL, mediaID, locationX, locationY, URL, content, event, eventKey, recognition );
        String rtnMsg = '';
        //回复消息
        
        if(msgType.equals('text')){
           rtnMsg = handleText(inMsg);
        }
        RestContext.response.addHeader('Content-Type', 'text/plain');    
        RestContext.response.responseBody = Blob.valueOf(rtnMsg);

}

        
    private static String handleText(IncomingMsg msg){
        String keyword = msg.content;
        String strReply;
        String strResult;
        if(keyword.equals('文本')){
            strReply = '这是个文本消息';
            strResult = composeTextReply(msg, strReply);
        }
        else if(keyword.equals('图文') || keyword.equals('单图文')){
            WeChatNews news = new WeChatNews('苹果WWDC2014召开在即', '2014 年似乎将成为又一个“苹果之年”,热爱和不那么热爱苹果的人都对它的一举一动保持着关注和揣测——以下是苹果 WWDC 2014 的13大看点:', 'http://a.36krcnd.com/photo/2014/4e3ae0dac4884bb91934a689b72f8f8b.png', 'http://www.36kr.com/p/212479.html');
            List<WeChatNews> newsList = new List<WeChatNews>();
            newsList.add(news);
            strResult = composeNewsReply(msg, newsList);
        }
        else if(keyword.equals('多图文')){
            WeChatNews news1 = new WeChatNews('苹果WWDC2014召开在即', '2014年似乎将成为又一个苹果之年,热爱和不那么热爱苹果的人都对它的一举一动保持着关注和揣测——以下是苹果 WWDC 2014 的13大看点:', 'http://a.36krcnd.com/photo/2014/4e3ae0dac4884bb91934a689b72f8f8b.png', 'http://www.36kr.com/p/212479.html');
            WeChatNews news2 = new WeChatNews('Facebook CEO 马克·扎克伯格再做慈善,为湾区学校捐赠 1.2 亿美元', '据 re/code消息,Facebook CEO 马克·扎克伯格与妻子Priscilla Cha (中文名陈慧娴) 计划向湾区学校捐赠 1.2 亿美元。', 'http://a.36krcnd.com/photo/2014/e64d647389bfda39131e12fa9d606bb6.jpg', 'http://www.36kr.com/p/212476.html');
            WeChatNews news3 = new WeChatNews('Nokia收购Siri的同门师弟Desti,为自家地图业务HERE融入更多人工智能', 'Nokia最近收购了一家地图公司Desti,来补强自家的地图业务HERE。', 'http://a.36krcnd.com/photo/2014/25490e2b8e63ced9586f0a432eebb972.jpg', 'http://www.36kr.com/p/212484.html');
            List<WeChatNews> newsList = new List<WeChatNews>();
            newsList.add(news1);
            newsList.add(news2);
            newsList.add(news3);
            strResult = composeNewsReply(msg, newsList);
        }
        else if(keyword.equals('音乐')){
            Map<String, String> music = new Map<String, String>();
            music.put('title', '爱你的宿命');
            music.put('description', '张信哲');
            music.put('musicUrl', 'http://zhangmenshiting.baidu.com/data2/music/119826740/1197655931401552061128.mp3?xcode=80587c819993d49621a8dce05e5bb8c9e36664380262dc7e&song_id=119765593');
            music.put('musicHQUrl', 'http://zhangmenshiting.baidu.com/data2/music/119826740/1197655931401552061128.mp3?xcode=80587c819993d49621a8dce05e5bb8c9e36664380262dc7e&song_id=119765593');
            strResult = composeMusicReply(msg, music);            
        }
        return strResult;
    }

    private static String composeTextReply(IncomingMsg msg,String rlyMSG)
    {
        String replyMSG = '<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content></xml>';
        String[] arguments = new String[]{msg.fromUserName, msg.toUserName, rlyMSG};
        String results = String.format(replyMSG, arguments);
        return results;
    }

    private static String composeNewsReply(IncomingMsg msg, List<WeChatNews> newsList){
        String strNews = '';
        String newsTpl = '<item><Title><![CDATA[{0}]]></Title><Description><![CDATA[{1}]]></Description><PicUrl><![CDATA[{2}]]></PicUrl><Url><![CDATA[{3}]]></Url></item>';
        for(WeChatNews news : newsList){
            String[] arguments = new String[]{news.title, news.description, news.picUrl, news.url};
            strNews += String.format(newsTpl, arguments);
        }
        String strTmp = '<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>1234567890</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount><![CDATA[{2}]]></ArticleCount><Articles>' + strNews + '</Articles></xml>';
        String[] arguments = new String[]{msg.fromUserName, msg.toUserName, String.valueOf(newsList.size())};
        String results = String.format(strTmp, arguments);
        return results;
    }

    private static String composeMusicReply(IncomingMsg msg, Map<String, String> music){
        String strTitle = music.get('title');
        String strDesc = music.get('description');
        String strURL = music.get('musicUrl');
        String strHQURL = music.get('musicHQUrl');
        String musicTpl = '<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[music]]></MsgType><Music><Title><![CDATA[{2}]]></Title><Description><![CDATA[{3}]]></Description><MusicUrl><![CDATA[{4}]]></MusicUrl><HQMusicUrl><![CDATA[{5}]]></HQMusicUrl></Music></xml>';
        String[] arguments = new String[]{msg.fromUserName, msg.toUserName, strTitle, strDesc, strURL, strHQURL};
        String results = String.format(musicTpl, arguments);
        return results;
    }

        /*****内部类****/
        public class IncomingMsg{
        public String toUserName;
        public String fromUserName;
        public String msgType;
        public String picURL;
        public String mediaID;
        public String locationX;
        public String locationY;
        public String URL;
        public String content;
        public String event;
        public String eventKey;
        public String recognition;
    
        public IncomingMsg(){}
        
        public IncomingMsg(String tUN, String fUN, String mT, String pU, String mI, String lX, String lY, String u, String c, String e, String eK, String r){
            this.toUserName = tUN;
            this.fromUserName = fUN;
            this.msgType = mT;
            this.picURL = pU;
            this.mediaID = mI;
            this.locationX = lX;
            this.locationY = lY;
            this.URL = u;
            this.content = c;
            this.event = e;
            this.eventKey = eK;
            this.recognition = r;
        }
        }

        public class WeChatNews{
        public String title;
        public String description;
        public String picUrl;
        public String url;
        
        public WeChatNews(){}
        
        public WeChatNews(String t, String d, String p, String u){
            this.title = t;
            this.description = d;
            this.picUrl = p;
            this.url = u;
        }
        }
        /**************/
    
}


共有 人打赏支持
粉丝 0
博文 1
码字总数 0
×
Wenchster
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: