search
HomeWeChat AppletWeChat DevelopmentForce.com WeChat development series applies for test accounts and responds to graphic messages

In addition to simple text message replies, Force.com can also reply to messages with pictures and texts, reply to music or videos, recognize voices sent by users, collect users' geographical location information and provide corresponding content or Services, etc., this article will explain these skills one by one. Before that, we must first introduce how to apply for a test account with all service account interface functions (although this is not necessary for replying to graphic messages).

Apply for a test account

As an individual developer, you can apply for a subscription account. The subscription account only opens the basic interface, including receiving user messages, replying to users, and Accept events (event push has follow or unfollow, scan QR code with parameters (generating such QR code requires advanced interface), report geographical location (not supported by ordinary subscription account), custom menu (not supported by ordinary subscription account) ) click) push three interfaces, but advanced functions such as custom menus, speech recognition, customer service interfaces, OAuth2.0 web page authorization, obtaining user geographical location information, etc. all require service accounts to support, among which certified subscription accounts Support custom menu. In order to facilitate developers to understand and learn these interfaces of Tencent, like any platform company, Tencent finally opened applications for test accounts late last year. Anyone with a WeChat subscription account can apply (a service account should also be possible, but I haven’t seen what the backend of a service account looks like, so I won’t comment).

The application method is simple and direct. After entering the WeChat backend (https://mp.weixin.qq.com), there is a After clicking on the "Developer Center" link, you will find a link to "Interface Test Application System Click to Enter". After clicking to enter, you can apply according to Tencent's ideas. I will not go into details here.

Force.com WeChat development series applies for test accounts and responds to graphic messages

What the application will look like after successful login is as follows. You can see it here. You can also see a two when scrolling the page. QR code, scan this QR code through WeChat to follow this test account, which supports up to 20 test users. After successful follow-up, there will be an additional account called "WeChat Public Platform Test Account" in the WeChat "Subscription Account" folder , note that although it is in the "Subscription Account" folder, it has the functions of all service accounts:

Force.com WeChat development series applies for test accounts and responds to graphic messagesFor the next work, here we first build several key classes and corresponding processing frameworks to facilitate the subsequent addition of more functional support. Force.com WeChat development series applies for test accounts and responds to graphic messages

IncomingMsg: The message class sent by the user, including various key field information;

WeChatNews: The news class when replying to news with pictures and texts;

The IncomingMsg class code is as follows, 12 fields, including most of the field information of various message types:

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;
    }
}
The definition code of the WeChatNews class is as follows, including the detailed definition information of a news:

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;
    }
}
Next, In the doPost method, we will use the XML parsing code in the last blog post tonight to enable it to parse any type of WeChat XML document. The modified doPost method is as follows:

global static void doPost(){
        //Receive message from user;
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        string strMsg = req.requestBody.toString();  
        System.debug('Request Contents' + strMsg);
        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 = '';
        
        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 inMsg = new IncomingMsg(toUserName, fromUserName, msgType, picURL, mediaID, locationX, locationY, URL, content, event, eventKey, recognition );
}
In this method, we will parse all types of WeChat XML documents. The fields in the WeChat message XML text are parsed, and the IncomingMsg object is initialized through the parsed value. Next, we will pass this object to call different methods to complete various tasks. Next, we add the following code at the end of the above doPost method:

String rtnMsg = '';
//回复消息

if(msgType.equals('text')){
   rtnMsg = handleText(inMsg);
}
RestContext.response.addHeader('Content-Type', 'text/plain');    
RestContext.response.responseBody = Blob.valueOf(rtnMsg);

This code first defines a String that stores the returned XML text. string, and then determine if the message type sent by the user is a text type, then call a handleText method to process the reply message. The object passed to the handleText method here is the IncomingMsg object we defined earlier. We will discuss the details of this method below. This section will introduce it again. After successfully obtaining the return string of this method, the XML text message can be returned to Tencent WeChat through RestContext, and further returned to the user who sent the message.

Detailed explanation of handleText method for sending images and text

Next we will introduce how to reply to image and text messages. Note that you do not need to apply for a test account to reply to graphic messages, just a regular subscription account. The following is the full code of this method:

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> music = new Map<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;
    }</string></string></wechatnews></wechatnews></wechatnews></wechatnews>

代码的思路应该来说比较直接,从第4行的if开始判断用户发送过来的文本是什么,根据不同的关键字来确定不同的返回内容,第一个if里将返回给用户单图文信息,这里先构造了一个WeChatNews数组,当然数组里只有一个WeChatNews对象,将这个数组交给composeNewsReply来完成最终的XML文构建;第一个else if也很类似,只不过这里的WeChatNews数组里有三条新闻,关于composeNewsReply方法的细节我们稍后介绍;最后一个else if里展示了如何回复音乐,这里我们构建了一个Map对象存储音乐的详情,并调用composeMusicReply方法来完成最终的XML文构建,同样该方法的细节稍后就会介绍到。

上面的思路应该来说还是比较清楚的,接下来介绍composeNewsReply方法的全部代码:

private static String composeNewsReply(IncomingMsg msg, List<wechatnews> newsList){
        String strNews = '';
        String newsTpl = '<item><title></title>
<description></description><picurl></picurl><url></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></tousername><fromusername></fromusername><createtime>1234567890</createtime><msgtype></msgtype><articlecount></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;
}</wechatnews>

 

了解该方法代码前先要了解回复图文信息的XML格式,关于此点可以参照腾讯公司链接:回复图文消息 ,与前文介绍到的普通文本消息大同小异,可以留意到里面有个ArticleCount字段用来指定回复的消息里能有几条图文新闻,最大是10,超过10则会无法响应;另外Article节点下方每一个item均是一条图文消息。为此,上述代码的第3行先构造一个每条新闻的模板,接着从第4行开始轮询新闻列表里的每一条新闻,并构造相应的XML文。从第8行开始构造整个图文回复的字符串模板,并在第9、10行通过相应参数将模板转换为最终的XML字符串。

再接下来介绍composeMusicReply,该方法的全部代码如下:

private static String composeMusicReply(IncomingMsg msg, Map<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></tousername><fromusername></fromusername><createtime>12345678</createtime><msgtype></msgtype><music><title></title>
<description></description><musicurl></musicurl><hqmusicurl></hqmusicurl></music></xml>';
        String[] arguments = new String[]{msg.fromUserName, msg.toUserName, strTitle, strDesc, strURL, strHQURL};
        String results = String.format(musicTpl, arguments);
        return results;
}</string>

同样了解该方法要首先了解回复音乐信息的XML格式,可以参照腾讯公司链接:回复音乐消息,上面代码与前面方法比较类似,就不再赘述。(这里的Map对象也许有点多余,可以考虑是否可以和回复视频的方法整合到一起,否则不需要额外的Map对象开销,直接将标题、描述、链接等信息传给composeMusicReply方法即可)。

运行效果

 

完成后直接保存代码便可立即生效,回复图文、多图文、音乐的运行效果分别如下:

Force.com WeChat development series applies for test accounts and responds to graphic messages          Force.com WeChat development series applies for test accounts and responds to graphic messages          Force.com WeChat development series applies for test accounts and responds to graphic messages

更多Force.com WeChat development series applies for test accounts and responds to graphic messages相关文章请关注PHP中文网!

 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP微信开发:如何实现消息加密解密PHP微信开发:如何实现消息加密解密May 13, 2023 am 11:40 AM

PHP是一种开源的脚本语言,广泛应用于Web开发和服务器端编程,尤其在微信开发中得到了广泛的应用。如今,越来越多的企业和开发者开始使用PHP进行微信开发,因为它成为了一款真正的易学易用的开发语言。在微信开发中,消息的加密和解密是一个非常重要的问题,因为它们涉及到数据的安全性。对于没有加密和解密方式的消息,黑客可以轻松获取到其中的数据,对用户造成威胁

PHP微信开发:如何实现客服聊天窗口管理PHP微信开发:如何实现客服聊天窗口管理May 13, 2023 pm 05:51 PM

微信是目前全球用户规模最大的社交平台之一,随着移动互联网的普及,越来越多的企业开始意识到微信营销的重要性。在进行微信营销时,客服服务是至关重要的一环。为了更好地管理客服聊天窗口,我们可以借助PHP语言进行微信开发。一、PHP微信开发简介PHP是一种开源的服务器端脚本语言,广泛运用于Web开发领域。结合微信公众平台提供的开发接口,我们可以使用PHP语言进行微信

PHP微信开发:如何实现用户标签管理PHP微信开发:如何实现用户标签管理May 13, 2023 pm 04:31 PM

在微信公众号开发中,用户标签管理是一个非常重要的功能,可以让开发者更好地了解和管理自己的用户。本篇文章将介绍如何使用PHP实现微信用户标签管理功能。一、获取微信用户openid在使用微信用户标签管理功能之前,我们首先需要获取用户的openid。在微信公众号开发中,通过用户授权的方式获取openid是比较常见的做法。在用户授权完成后,我们可以通过以下代码获取用

用PHP开发微信群发工具用PHP开发微信群发工具May 13, 2023 pm 05:00 PM

随着微信的普及,越来越多的企业开始将其作为营销工具。而微信群发功能,则是企业进行微信营销的重要手段之一。但是,如果只依靠手动发送,对于营销人员来说是一件极为费时费力的工作。所以,开发一款微信群发工具就显得尤为重要。本文将介绍如何使用PHP开发微信群发工具。一、准备工作开发微信群发工具,我们需要掌握以下几个技术点:PHP基础知识微信公众平台开发开发工具:Sub

如何使用PHP进行微信开发?如何使用PHP进行微信开发?May 21, 2023 am 08:37 AM

随着互联网和移动智能设备的发展,微信成为了社交和营销领域不可或缺的一部分。在这个越来越数字化的时代,如何使用PHP进行微信开发已经成为了很多开发者的关注点。本文主要介绍如何使用PHP进行微信开发的相关知识点,以及其中的一些技巧和注意事项。一、开发环境准备在进行微信开发之前,首先需要准备好相应的开发环境。具体来说,需要安装PHP的运行环境,以及微信公众平台提

PHP微信开发:如何实现群发消息发送记录PHP微信开发:如何实现群发消息发送记录May 13, 2023 pm 04:31 PM

随着微信成为了人们生活中越来越重要的一个通讯工具,其敏捷的消息传递功能迅速受到广大企业和个人的青睐。对于企业而言,将微信发展为一个营销平台已经成为趋势,而微信开发的重要性也逐渐凸显。在其中,群发功能更是被广泛使用,那么,作为PHP程序员,如何实现群发消息发送记录呢?下面将为大家简单介绍一下。1.了解微信公众号相关开发知识在了解如何实现群发消息发送记录之前,我

ThinkPHP6微信开发指南:快速搭建微信公众号应用ThinkPHP6微信开发指南:快速搭建微信公众号应用Aug 26, 2023 pm 11:55 PM

ThinkPHP6微信开发指南:快速搭建微信公众号应用引言:微信公众号作为一种重要的社交媒体平台,为个人和企业在市场推广、信息传播等方面提供了很大的机会。在这篇文章中,我们将介绍如何使用ThinkPHP6快速搭建一个微信公众号应用,并且提供一些常用的代码示例。环境准备在开始开发之前,我们首先需要准备好以下环境:PHP7以上版本ThinkPHP6框架微信公众号

PHP微信开发:如何实现语音识别PHP微信开发:如何实现语音识别May 13, 2023 pm 09:31 PM

随着移动互联网的普及,微信作为一款社交软件,越来越多的人开始使用,并且微信开放平台也给开发者带来了众多的机会。近年来,随着人工智能技术的发展,语音识别技术逐渐成为了移动端开发的热门技术之一。在微信开发中,如何实现语音识别成为很多开发者关注的问题。本文将介绍如何利用PHP开发微信应用实现语音识别功能。一、语音识别原理在介绍如何实现语音识别之前,我们先了解一下语

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment