


Chapter 5 has already talked about how to handle messages sent by users. This chapter will talk about how to respond to user requests. Novices must be confused when they see this title. Don’t be confused. The interface of WeChat is just like this. When replying to pictures, music, voice, etc., we need to upload our media files to the WeChat server before we can use it. I don’t know what the considerations are for this approach, and the message body formats sent by the customer service interface and the group sending interface are actually different when replying to messages to users. It is estimated that these interfaces were not written by the same person, and the code was not unified. We loser developers can only complain.
Before talking about the upload and download interface, we need to first talk about the access_token acquisition method. In the process of WeChat interface development, access_token is crucial. It is the globally unique ticket of the official account. The official account needs to use access_token when calling each interface. Developers need to store it properly. At least 512 characters of space must be reserved for access_token storage. The validity period of access_token is currently 2 hours and needs to be refreshed regularly. Repeated acquisition will cause the last access_token to become invalid. It should be noted that there is only one valid access_token for an official account at the same time, and developers need to refresh the access_token before the access_token expires. During the refresh process, the public platform backend will ensure that both the old and new access_tokens are available within a short time of refresh, which ensures a smooth transition of third-party services.
The public account can use AppID and AppSecret to call this interface to obtain access_token. AppID and AppSecret can be obtained from the official website of WeChat Public Platform - Developer Center page (you need to have become a developer, and the account has no abnormal status). As shown below:
The interface address for obtaining access_token is:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
將appid和secret替換成你自己的。
Send a get request to this address, and the returned data is as follows:
{"access_token":"eEd6dhp0s24JfWwDyGBbrvJxnhqHTSYZ8MKdQ7MuCGBKxAjHv-tEIwhFZzn102lGvIWxnjZZreT6C1NCT9fpS7NREOkEX42yojVnqKVaicg","expires_in":7200}
我們只需解析這個json,即可獲取到我們所需的access_token.代碼如下:
AccessToken實體類:
public class AccessToken { public string token { get; set; } public DateTime expirestime { get; set; } }
Get access token
/// <summary> /// 獲取access token /// </summary> /// <param name="appid">第三方用戶唯一憑證</param> /// <param name="secret">第三方用戶唯一憑證密鑰,即appsecret</param> /// <returns>AccessToken對象,expirestime是過期時間</returns> public static AccessToken GetAccessToken(string appid, string secret) { try { string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret); string retdata = Utils.HttpGet(url); if (retdata.Contains("access_token")) { JObject obj = (JObject)JsonConvert.DeserializeObject(retdata); string token = obj.Value<string>("access_token"); int expirestime = obj.Value<int>("expires_in"); return new AccessToken { token = token, expirestime = DateTime.Now.AddSeconds(expirestime) }; } else { WriteBug(retdata);//寫錯誤日志 } return null; } catch (Exception e) { WriteBug(e.ToString());//寫錯誤日志 return null; } }
After successfully obtaining the access_token, let’s upload and download multimedia files. The official said that when the official account uses the interface, operations such as obtaining and calling multimedia files and multimedia messages are performed through media_id (I don’t know much about reading, so I don’t understand why the URL cannot be used, but it is unnecessary to upload it to the server before sending. ). Through this interface, public accounts can upload or download multimedia files. But please note that each multimedia file (media_id) will be automatically deleted 3 days after it is uploaded and sent to the WeChat server by the user to save server resources.
The interface address for uploading multimedia is:
file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE
where access_token is the calling interface certificate, type is the media file type, including WeChat development passive reply and upload and download files, voice, VIDEO (video) and THUMBNAIL (thumb)
NOTES :
Uploaded multimedia files have format and size restrictions , as follows:
Picture (WeChat development passive reply and upload and download files): 1M, supports JPG format
Voice (voice): 2M, playback length does not exceed 60s, Support AMR\MP3 format
Video (video): 10MB, support MP4 format
Thumbnail (thumb): 64KB, support JPG format
#Media files are saved in the background for 3 days, that is, the media_id will expire after 3 days.
In order to facilitate calling, define the type of media file as an enumeration, the code is as follows:
public enum MediaType { /// <summary> /// 圖片(WeChat development passive reply and upload and download files): 1M,支持JPG格式 /// </summary> WeChat development passive reply and upload and download files, /// <summary> /// 語音(voice):2M,播放長度不超過60s,支持AMR\MP3格式 /// </summary> voice, /// <summary> /// 視頻(video):10MB,支持MP4格式 /// </summary> video, /// <summary> /// 縮略圖(thumb):64KB,支持JPG格式 /// </summary> thumb }
Then define the type of the return value:
public class UpLoadInfo { /// <summary> /// 媒體文件類型,分別有圖片(WeChat development passive reply and upload and download files)、語音(voice)、視頻(video)和縮略圖(thumb,主要用于視頻與音樂格式的縮略圖) /// </summary> public string type { get; set; } /// <summary> /// 媒體文件上傳后,獲取時的唯一標識 /// </summary> public string media_id { get; set; } /// <summary> /// 媒體文件上傳時間戳 /// </summary> public string created_at { get; set; } }
Finally use WebClient class to upload files and read out the return value. The code is as follows:
/// <summary> /// 微信上傳多媒體文件 /// </summary> /// <param name="filepath">文件絕對路徑</param> public static ReceiveModel.UpLoadInfo WxUpLoad(string filepath, string token, MediaType mt) { using (WebClient client = new WebClient()) { byte[] b = client.UploadFile(string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", token, mt.ToString()), filepath);//調(diào)用接口上傳文件 string retdata = Encoding.Default.GetString(b);//獲取返回值 if (retdata.Contains("media_id"))//判斷返回值是否包含media_id,包含則說明上傳成功,然后將返回的json字符串轉(zhuǎn)換成json { return JsonConvert.DeserializeObject<UpLoadInfo>(retdata); } else {//否則,寫錯誤日志 WriteBug(retdata);//寫錯誤日志 return null; } } }
At this point, before talking about replying to the message, two basic support interfaces have been inserted. Since your ability to organize and summarize is so bad, please read it. Please bear with me. If you have any questions, please leave a message and communicate with me. Let’s officially start talking about replying to messages. When reading the following content, please read it in conjunction with Chapters 4 and 5.
The previous two chapters talked about receiving and processing messages sent by users, and talked about a message base class BaseMessage. No matter what type of message we receive, we need to be able to call methods to respond to user requests, so , the method for users to reply to user requests needs to be encapsulated into a base class. Let’s take a brief look at the types of messages that public accounts can reply to, as well as the message formats.
Note:
Once the following situation occurs, WeChat will issue a system prompt to the user in the public account session "This public account is temporarily unavailable. Service, please try again later":
1、開發(fā)者在5秒內(nèi)未回復任何內(nèi)容 2、開發(fā)者回復了異常數(shù)據(jù),比如JSON數(shù)據(jù)等
回復文本消息
<xml><ToUserName><![CDATA[接收方帳號(收到的OpenID)]]></ToUserName><FromUserName><![CDATA[開發(fā)者微信號]]></FromUserName><CreateTime>消息創(chuàng)建時間 (整型)</CreateTime><MsgType><![CDATA[WeChat development passive reply and upload and download files]]></MsgType><Content><![CDATA[回復的消息內(nèi)容(換行:在content中能夠換行,微信客戶端就支持換行顯示)]]></Content></xml>
回復圖片消息
<xml><ToUserName><![CDATA[接收方帳號(收到的OpenID)]]></ToUserName><FromUserName><![CDATA[開發(fā)者微信號]]></FromUserName><CreateTime>消息創(chuàng)建時間 (整型)</CreateTime><MsgType><![CDATA[WeChat development passive reply and upload and download files]]></MsgType><Image><MediaId><![CDATA[通過上傳多媒體文件,得到的id。]]></MediaId></Image></xml>
回復語音消息
<xml><ToUserName><![CDATA[接收方帳號(收到的OpenID)]]></ToUserName><FromUserName><![CDATA[開發(fā)者微信號]]></FromUserName><CreateTime>消息創(chuàng)建時間 (整型)</CreateTime><MsgType><![CDATA[voice]]></MsgType><Voice><MediaId><![CDATA[通過上傳多媒體文件,得到的id。]]></MediaId></Voice></xml>
回復視頻消息
<xml><ToUserName><![CDATA[接收方帳號(收到的OpenID)]]></ToUserName><FromUserName><![CDATA[開發(fā)者微信號]]></FromUserName><CreateTime>消息創(chuàng)建時間 (整型)</CreateTime><MsgType><![CDATA[video]]></MsgType><Video><MediaId><![CDATA[通過上傳多媒體文件,得到的id。]]></MediaId><Title><![CDATA[視頻消息的標題]]></Title> <Description><![CDATA[視頻消息的描述]]></Description> </Video></xml>
回復音樂消息
<xml><ToUserName><![CDATA[接收方帳號(收到的OpenID)]]></ToUserName><FromUserName><![CDATA[開發(fā)者微信號]]></FromUserName><CreateTime>消息創(chuàng)建時間 (整型)</CreateTime><MsgType><![CDATA[music]]></MsgType><Music><ThumbMediaId><![CDATA[縮略圖的媒體id,通過上傳多媒體文件,得到的id。]]></ThumbMediaId><Title><![CDATA[視頻消息的標題]]></Title> <Description><![CDATA[視頻消息的描述]]></Description> <MusicURL><![CDATA[音樂鏈接]]></MusicURL> <HQMusicUrl><![CDATA[高質(zhì)量音樂鏈接,WIFI環(huán)境優(yōu)先使用該鏈接播放音樂]]></HQMusicUrl> </Music></xml>
回復圖文消息
<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>2</ArticleCount><Articles><item><Title><![CDATA[title1]]></Title> <Description><![CDATA[description1]]></Description><PicUrl><![CDATA[picurl]]></PicUrl><Url><![CDATA[url]]></Url></item><item><Title><![CDATA[title]]></Title><Description><![CDATA[description]]></Description><PicUrl><![CDATA[picurl]]></PicUrl><Url><![CDATA[url]]></Url></item></Articles></xml>
回復圖文中,item是一個項,一個item代碼一個圖文。在響應的時候,我們只需根據(jù)數(shù)據(jù)格式,替換掉對應的屬性,然后Response.Write(s)即可。結合前兩章的講解,BaseMessage的最終代碼如下:
/// <summary> /// 消息體基類 /// </summary> public abstract class BaseMessage { /// <summary> /// 開發(fā)者微信號 /// </summary> public string ToUserName { get; set; } /// <summary> /// 發(fā)送方帳號(一個OpenID) /// </summary> public string FromUserName { get; set; } /// <summary> /// 消息創(chuàng)建時間 (整型) /// </summary> public string CreateTime { get; set; } /// <summary> /// 消息類型 /// </summary> public MsgType MsgType { get; set; } public virtual void ResponseNull() { Utils.ResponseWrite(""); } public virtual void ResText(EnterParam param, string content) { StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>", FromUserName, ToUserName, Utils.ConvertDateTimeInt(DateTime.Now))); resxml.AppendFormat("<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{0}]]></Content><FuncFlag>0</FuncFlag></xml>", content); Response(param, resxml.ToString()); } /// <summary> /// 回復消息(音樂) /// </summary> public void ResMusic(EnterParam param, Music mu) { StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>",FromUserName,ToUserName, Utils.ConvertDateTimeInt(DateTime.Now))); resxml.Append(" <MsgType><![CDATA[music]]></MsgType>"); resxml.AppendFormat("<Music><Title><![CDATA[{0}]]></Title><Description><![CDATA[{1}]]></Description>", mu.Title, mu.Description); resxml.AppendFormat("<MusicUrl><![CDATA[http://{0}{1}]]></MusicUrl><HQMusicUrl><![CDATA[http://{2}{3}]]></HQMusicUrl></Music><FuncFlag>0</FuncFlag></xml>", VqiRequest.GetCurrentFullHost(), mu.MusicUrl, VqiRequest.GetCurrentFullHost(), mu.HQMusicUrl); Response(param, resxml.ToString()); } public void ResVideo(EnterParam param, Video v) { StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>",FromUserName,ToUserName, Utils.ConvertDateTimeInt(DateTime.Now))); resxml.Append(" <MsgType><![CDATA[video]]></MsgType>"); resxml.AppendFormat("<Video><MediaId><![CDATA[{0}]]></MediaId>", v.media_id); resxml.AppendFormat("<Title><![CDATA[{0}]]></Title>", v.title); resxml.AppendFormat("<Description><![CDATA[{0}]]></Description></Video></xml>", v.description); Response(param, resxml.ToString()); } /// <summary> /// 回復消息(圖片) /// </summary> public void ResPicture(EnterParam param, Picture pic, string domain) { StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>",FromUserName,ToUserName, Utils.ConvertDateTimeInt(DateTime.Now))); resxml.Append(" <MsgType><![CDATA[WeChat development passive reply and upload and download files]]></MsgType>"); resxml.AppendFormat("<PicUrl><![CDATA[{0}]]></PicUrl></xml>", domain + pic.PictureUrl); Response(param, resxml.ToString()); } /// <summary> /// 回復消息(圖文列表) /// </summary> /// <param name="param"></param> /// <param name="art"></param> public void ResArticles(EnterParam param, List<Articles> art) { StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>",FromUserName,ToUserName, Utils.ConvertDateTimeInt(DateTime.Now))); resxml.AppendFormat("<MsgType><![CDATA[news]]></MsgType><ArticleCount>{0}</ArticleCount><Articles>", art.Count); for (int i = 0; i < art.Count; i++) { resxml.AppendFormat("<item><Title><![CDATA[{0}]]></Title> <Description><![CDATA[{1}]]></Description>", art[i].Title, art[i].Description); resxml.AppendFormat("<PicUrl><![CDATA[{0}]]></PicUrl><Url><![CDATA[{1}]]></Url></item>", art[i].PicUrl.Contains("http://") ? art[i].PicUrl : "http://" + VqiRequest.GetCurrentFullHost() + art[i].PicUrl, art[i].Url.Contains("http://") ? art[i].Url : "http://" + VqiRequest.GetCurrentFullHost() + art[i].Url); } resxml.Append("</Articles><FuncFlag>0</FuncFlag></xml>"); Response(param, resxml.ToString()); } /// <summary> /// 多客服轉(zhuǎn)發(fā) /// </summary> /// <param name="param"></param> public void ResDKF(EnterParam param) { StringBuilder resxml = new StringBuilder(); resxml.AppendFormat("<xml><ToUserName><![CDATA[{0}]]></ToUserName>",FromUserName); resxml.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName><CreateTime>{1}</CreateTime>",ToUserName,CreateTime); resxml.AppendFormat("<MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>"); Response(param, resxml.ToString()); } /// <summary> /// 多客服轉(zhuǎn)發(fā)如果指定的客服沒有接入能力(不在線、沒有開啟自動接入或者自動接入已滿),該用戶會一直等待指定客服有接入能力后才會被接入,而不會被其他客服接待。建議在指定客服時,先查詢客服的接入能力指定到有能力接入的客服,保證客戶能夠及時得到服務。 /// </summary> /// <param name="param">用戶發(fā)送的消息體</param> /// <param name="KfAccount">多客服賬號</param> public void ResDKF(EnterParam param, string KfAccount) { StringBuilder resxml = new StringBuilder(); resxml.AppendFormat("<xml><ToUserName><![CDATA[{0}]]></ToUserName>",FromUserName); resxml.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName><CreateTime>{1}</CreateTime>",ToUserName,CreateTime); resxml.AppendFormat("<MsgType><![CDATA[transfer_customer_service]]></MsgType><TransInfo><KfAccount>{0}</KfAccount></TransInfo></xml>", KfAccount); Response(param, resxml.ToString()); } private void Response(EnterParam param, string data) { if (param.IsAes) { var wxcpt = new MsgCrypt(param.token, param.EncodingAESKey, param.appid); wxcpt.EncryptMsg(data, Utils.ConvertDateTimeInt(DateTime.Now).ToString(), Utils.GetRamCode(), ref data); } Utils.ResponseWrite(data); } }
上面的代碼中,public void ResDKF(EnterParam param),public void ResDKF(EnterParam param, string KfAccount)兩個方法時多客服中,用戶轉(zhuǎn)發(fā)用戶發(fā)送的消息的,多客服將在后期的博文中進行更新,敬請期待。
public void ResMusic(EnterParam param, Music mu)方法中的Music類的定義如下:
public class Music { #region 屬性 /// <summary> /// 音樂鏈接 /// </summary> public string MusicUrl { get; set; } /// <summary> /// 高質(zhì)量音樂鏈接,WIFI環(huán)境優(yōu)先使用該鏈接播放音樂 /// </summary> public string HQMusicUrl { get; set; } /// <summary> /// 標題 /// </summary> public string Title { get; set; } /// <summary> /// 描述 /// </summary> public string Description { get; set; } #endregion }
public void ResVideo(EnterParam param, Video v)方法中的Video類的定義如下:
public class Video { public string title { get; set; } public string media_id { get; set; } public string description { get; set; } }
public void ResArticles(EnterParam param, List
public class Articles { #region 屬性 /// <summary> /// 圖文消息標題 /// </summary> public string Title { get; set; } /// <summary> /// 圖文消息描述 /// </summary> public string Description { get; set; } /// <summary> /// 圖片鏈接,支持JPG、PNG格式,較好的效果為大圖640*320,小圖80*80。 /// </summary> public string PicUrl { get; set; } /// <summary> /// 點擊圖文消息跳轉(zhuǎn)鏈接 /// </summary> public string Url { get; set; } #endregion }
【相關推薦】
2.微信投票源碼
The above is the detailed content of WeChat development passive reply and upload and download files. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

In the development of WeChat public accounts, the voting function is often used. The voting function is a great way for users to quickly participate in interactions, and it is also an important tool for holding events and surveying opinions. This article will introduce you how to use PHP to implement WeChat voting function. Obtain the authorization of the WeChat official account. First, you need to obtain the authorization of the WeChat official account. On the WeChat public platform, you need to configure the API address of the WeChat public account, the official account, and the token corresponding to the public account. In the process of our development using PHP language, we need to use the PH officially provided by WeChat

With the popularity of WeChat, more and more companies are beginning to use it as a marketing tool. The WeChat group messaging function is one of the important means for enterprises to conduct WeChat marketing. However, if you only rely on manual sending, it is an extremely time-consuming and laborious task for marketers. Therefore, it is particularly important to develop a WeChat mass messaging tool. This article will introduce how to use PHP to develop WeChat mass messaging tools. 1. Preparation work To develop WeChat mass messaging tools, we need to master the following technical points: Basic knowledge of PHP WeChat public platform development Development tools: Sub

WeChat is currently one of the social platforms with the largest user base in the world. With the popularity of mobile Internet, more and more companies are beginning to realize the importance of WeChat marketing. When conducting WeChat marketing, customer service is a crucial part. In order to better manage the customer service chat window, we can use PHP language for WeChat development. 1. Introduction to PHP WeChat development PHP is an open source server-side scripting language that is widely used in the field of Web development. Combined with the development interface provided by WeChat public platform, we can use PHP language to conduct WeChat

In the development of WeChat public accounts, user tag management is a very important function, which allows developers to better understand and manage their users. This article will introduce how to use PHP to implement the WeChat user tag management function. 1. Obtain the openid of the WeChat user. Before using the WeChat user tag management function, we first need to obtain the user's openid. In the development of WeChat public accounts, it is a common practice to obtain openid through user authorization. After the user authorization is completed, we can obtain the user through the following code

As WeChat becomes an increasingly important communication tool in people's lives, its agile messaging function is quickly favored by a large number of enterprises and individuals. For enterprises, developing WeChat into a marketing platform has become a trend, and the importance of WeChat development has gradually become more prominent. Among them, the group sending function is even more widely used. So, as a PHP programmer, how to implement group message sending records? The following will give you a brief introduction. 1. Understand the development knowledge related to WeChat public accounts. Before understanding how to implement group message sending records, I

How to use PHP to develop WeChat public accounts WeChat public accounts have become an important channel for promotion and interaction for many companies, and PHP, as a commonly used Web language, can also be used to develop WeChat public accounts. This article will introduce the specific steps to use PHP to develop WeChat public accounts. Step 1: Obtain the developer account of the WeChat official account. Before starting the development of the WeChat official account, you need to apply for a developer account of the WeChat official account. For the specific registration process, please refer to the official website of WeChat public platform

With the development of the Internet and mobile smart devices, WeChat has become an indispensable part of the social and marketing fields. In this increasingly digital era, how to use PHP for WeChat development has become the focus of many developers. This article mainly introduces the relevant knowledge points on how to use PHP for WeChat development, as well as some of the tips and precautions. 1. Development environment preparation Before developing WeChat, you first need to prepare the corresponding development environment. Specifically, you need to install the PHP operating environment and the WeChat public platform
