Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to passively reply and upload and download files developed by Wechat

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how Wechat development to achieve passive response and upload and download files, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article. Let's learn about it!

Before we talk about the upload / download interface, we need to talk about how to obtain access_token. The process of developing the Wechat interface, access_token, is very important. It is the only global ticket for the official account. When the official account calls each interface, it needs to use access_token. Developers need to save it properly. At least 512 character space should be reserved for access_token storage. The access_token is valid for 2 hours and needs to be refreshed regularly. Repeated acquisition will invalidate the last acquired access_token. It should be noted that only one valid access_token exists in an official account at the same time, and the developer needs to refresh the access_token before the access_token expires. During the refresh process, the public platform backend will ensure that both the new and old access_token are available within a short period of time, which ensures a smooth transition of third-party business.

The official account can use AppID and AppSecret to call this API to obtain access_token. AppID and AppSecret are available on the developer Center page, the official website of Wechat Public platform (you need to have become a developer and have no abnormal account status). As shown below:

The API address for obtaining access_token is:

Https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET replaces appid and secret with your own.

Send a get request to this address, and the data returned is as follows:

{"access_token": "eEd6dhp0s24JfWwDyGBbrvJxnhqHTSYZ8MKdQ7MuCGBKxAjHv-tEIwhFZzn102lGvIWxnjZZreT6C1NCT9fpS7NREOkEX42yojVnqKVaicg", "expires_in": 7200} We only need to parse this json to get the access_token we need. The code is as follows: AccessToken entity class: public class AccessToken {public string token {get; set;} public DateTime expirestime {get; set;}}

Get access token

/ get access token / third-party user unique credential key, that is, appsecret / AccessToken object Expirestime is the expiration time 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 ("access_token"); int expirestime = obj.Value ("expires_in") Return new AccessToken {token = token, expirestime = DateTime.Now.AddSeconds (expirestime)};} else {WriteBug (retdata); / / write error log} return null } catch (Exception e) {WriteBug (e.ToString ()); / / write error log return null;}}

After the success of access_token, let's upload and download multimedia files. Officials say that when using the interface, the official account acquires and invokes multimedia files and multimedia messages through media_id (we read less, I don't understand why we can't use url, but we have to upload to the server before sending). Through this interface, the official account can upload or download multimedia files. However, please note that each multimedia file (media_id) will be automatically deleted 3 days after uploading and sending to the Wechat server, in order 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

Access_token is the calling API credential, and type is the media file type, including picture (image), voice (voice), video (video) and thumbnail (thumb).

Note:

Uploaded multimedia files are limited in format and size, as follows:

Picture (image): 1m, supports JPG format

Voice (voice): 2m. Playback length is less than 60s. AMR\ MP3 format is supported.

Video (video): 10MB, which supports MP4 format

Thumbnails (thumb): 64KB, supporting JPG format

The media file is saved in the background for 3 days, that is, the media_id expires after 3 days.

To facilitate the call, define the type of the media file as an enumeration, as follows:

Public enum MediaType {/ Picture (image): 1m, support JPG format / image, / Voice (voice): 2m, playback length is not more than 60s, support AMR\ MP3 format / voice, / Video (video): 10MB Support MP4 format / / video, / thumbnail (thumb): 64KB, support JPG format / thumb}

Then define the type of return value:

Public class UpLoadInfo {/ media file type, including picture (image), voice (voice), video (video) and thumbnail (thumb, mainly used for video and music format thumbnails) / public string type {get; set } / after the media file is uploaded, the unique ID / public string media_id {get; set;} / media file upload timestamp / public string created_at {get; set;}}

Finally, use the WebClient class to upload the file and read out the return value. The code is as follows:

/ Wechat uploads multimedia files / absolute path to files 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) / / call API to upload file string retdata = Encoding.Default.GetString (b); / / get the return value if (retdata.Contains ("media_id")) / / determine whether the returned value contains media_id. If it is included, the upload is successful, and then convert the returned json string to json {return JsonConvert.DeserializeObject (retdata). } else {/ / otherwise, write error log WriteBug (retdata); / / write error log return null;}

At this point, before talking about the reply message, I have inserted two basic support interfaces. As your ability to organize and sum up is too bad, please forgive me and leave a message with me if you have any questions. Let's officially start with the reply message. When reading the following content, please combine the fourth and fifth chapters to read.

The first two chapters talk about receiving and processing messages sent by users, and talk about a message base class BaseMessage, and no matter what type of messages we receive, we need to be able to call methods to respond to users' requests, so the methods that users reply to users' requests need to be encapsulated in the base class. Let's take a brief look at the types of messages that the official account can reply to, as well as the message format.

Note:

In case of the following situations, Wechat will send a system prompt to the user in the official account session: "the official account is temporarily unavailable, please try again later":

1. The developer did not reply anything within 5 seconds. 2. The developer replied to abnormal data, such as JSON data, etc., reply text message creation time (integer) reply picture message creation time (integer) reply voice message creation time (integer) reply video message creation time (integer) reply music message creation time (integer) reply picture and text message 123456782

Reply to the picture and text, item is an item, an item code a picture and text. In response, we just need to replace the corresponding attributes according to the data format, and then Response.Write (s). Combined with the explanation of the first two chapters, the final code of BaseMessage is as follows:

/ message body base class / public abstract class BaseMessage {peg / peg / developer Wechat / public string ToUserName {get; set;} / sender account (an OpenID) / public string FromUserName {get; set } / message creation time (integer) / public string CreateTime {get; set;} / 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 ("{2}", FromUserName, ToUserName, Utils.ConvertDateTimeInt (DateTime.Now)); resxml.AppendFormat ("0", content); Response (param, resxml.ToString ()) / reply message (music) / public void ResMusic (EnterParam param, Music mu) {StringBuilder resxml = new StringBuilder (string.Format ("{2}", FromUserName,ToUserName, Utils.ConvertDateTimeInt (DateTime.Now)); resxml.Append ("); resxml.AppendFormat (", mu.Title, mu.Description) Resxml.AppendFormat ("0", 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 ("{2}", FromUserName,ToUserName, Utils.ConvertDateTimeInt (DateTime.Now)); resxml.Append (") Resxml.AppendFormat (", v.media_id); resxml.AppendFormat (", v.title); resxml.AppendFormat (", v.description); Response (param, resxml.ToString ()) } / reply message (picture) / public void ResPicture (EnterParam param, Picture pic, string domain) {StringBuilder resxml = new StringBuilder (string.Format ("{2}", FromUserName,ToUserName, Utils.ConvertDateTimeInt (DateTime.Now)); resxml.Append ("); resxml.AppendFormat (", domain + pic.PictureUrl) Response (param, resxml.ToString ()); reply message (list of pictures and text) / public void ResArticles (EnterParam param, List art) {StringBuilder resxml = new StringBuilder (string.Format ("{2}", FromUserName,ToUserName, Utils.ConvertDateTimeInt (DateTime.Now) Resxml.AppendFormat ("{0}", art.Count); for (int I = 0; I < art.Count; iTunes +) {resxml.AppendFormat ("", art [I] .title, art [I] .description); resxml.AppendFormat ("", art [I] .PicUrl.Conclusion ("http://")? Art [I] .PicUrl: "http://" + VqiRequest.GetCurrentFullHost () + art [I] .PicUrl, art [I] .Url.Conclusion (" http://")? Resxml.Append [I] .URL: "http://" + VqiRequest.GetCurrentFullHost () + art [I] .URL);} URL (" 0 "); Response (param, URL ()) } / public void ResDKF (EnterParam param) {StringBuilder resxml = new StringBuilder (); resxml.AppendFormat (", FromUserName); resxml.AppendFormat (" {1} ", ToUserName,CreateTime); resxml.AppendFormat (") Response (param, resxml.ToString ());} / Multi-customer Service forwarding if the specified customer service does not have access capability (not online, does not enable automatic access, or automatic access is full), the user will wait for the specified customer service to have the access capability before it will be connected, and will not be received by other customer service. It is recommended that when assigning customer service, you should first inquire about the access capability of customer service and assign it to the customer service that has the ability to access, so as to ensure that customers can receive service in a timely manner. / / message body / multiple customer service account public void ResDKF (EnterParam param, string KfAccount) {StringBuilder resxml = new StringBuilder (); resxml.AppendFormat (", FromUserName); resxml.AppendFormat (" {1} ", ToUserName,CreateTime); resxml.AppendFormat (" {0} ", 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);}}

In the above code, when public void ResDKF (EnterParam param) and public void ResDKF (EnterParam param, string KfAccount) are used in multi-customer service, if the user forwards the messages sent by the user, the multi-customer service will be updated in a later blog post.

The Music class in the public void ResMusic (EnterParam param, Music mu) method is defined as follows:

Public class Music {# region attribute / Music Link / public string MusicUrl {get; set;} / High-quality Music Link, which is preferred by the WIFI environment to play music / public string HQMusicUrl {get; set } / title / public string Title {get; set;} / description / public string Description {get; set;} # endregion}

The Video class in the public void ResVideo (EnterParam param, Video v) method is defined as follows:

Public class Video {public string title {get; set;} public string media_id {get; set;} public string description {get; set;}}

The definition of Articles in public void ResArticles (EnterParam param, List art) is as follows:

Public class Articles {# region attribute / Teletext message title / public string Title {get; set;} / Teletext message description / public string Description {get; set } / Image link, which supports JPG and PNG formats. The better effect is 640 / 320 in big image and 80 / 80 in small image. / public string PicUrl {get; set;} / Click the link / public string Url {get; set;} # endregion} above is all the contents of the article "how to passively reply and upload and download files in Wechat development". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report