C # develop WeChat portals and applications (26)-WeChat materials management for public accounts,

Source: Internet
Author: User

C # development portal and application (26)-material management of public accounts,

The public account recently modified the management mode of materials and provided two types of materials: temporary materials and permanent materials. The original management of materials was temporary materials, permanent materials can be permanently retained on the server. After the materials are uploaded, they can be sent to image files or text messages. The public number of the materials concerned can be viewed within the validity period of the materials, for permanent materials, there will be no expiration issue, but it is only a limit on the quantity limit. This article introduces the various interfaces and implementations of material management in two aspects.

1. material types and functions

Official description of materials:

Temporary materials:

Public accounts often use temporary multimedia materials, such as obtaining and calling multimedia files and multimedia messages when using interfaces, especially when sending messages, it is carried out through media_id. The material management interface is open to all authenticated subscription numbers and service numbers. Through this interface, you can add temporary materials (that is, upload temporary multimedia files) to the public account ). For temporary materials, each clip (media_id) is automatically deleted three days after the developer uploads the materials or the fans send them to the server. The format and size of materials must be consistent with those on the official website of the public platform. Specifically, the image size cannot exceed 2 MB, supports bmp, png, jpeg, jpg, and gif formats, the speech size cannot exceed 5 MB, and the length cannot exceed 60 seconds, supports mp3, wma, wav, and amr formats.

Permanent materials:

In addition to temporary materials that will expire in three days, developers sometimes need to permanently save some materials, and then they can add permanent materials through this interface. The new permanent materials can also be viewed in the material management module on the official website of the public platform. There is a maximum number of permanent materials. Please be careful when adding new materials. The maximum size of text message materials and image materials is 5000, and that of other types is 1000.

 

Material management includes the following functions:

 

2. Definition and implementation of management interfaces for temporary materials

We define an IMediaApi interface to define relevant interface processing.

1) Upload temporary files

For uploading temporary files, the official interface definition is as follows.

API call request description

Http Request Method: POST/FORM. You need to use httpshttps: // api.weixin.qq.com/cgi-bin/media/upload? Access_token = ACCESS_TOKEN & type = TYPE call example (use the curl command to upload a multimedia file using FORM): curl-F media=@test.jpg "https://api.weixin.qq.com/cgi-bin/media/upload? Access_token = ACCESS_TOKEN & type = TYPE"

For processing uploaded temporary files, we can define its interface as follows.

/// <Summary> /// upload a temporary multimedia file. The format and size limit are as follows: // image: 1 MB. JPG format is supported. // voice: 2 MB. The playback length cannot exceed 60 s, supports the AMR \ MP3 format // video (10 MB), MP4 format // Thumbnail (thumb): 64KB, and JPG format. /// The media file is saved in the background for three days, that is, the media_id expires three days later. /// </Summary> /// <param name = "accessToken"> call interface creden< </param> /// <param name = "type"> media file type, images, voice, video, and thumb) </param> /// <param name = "file"> ID of a media file in form-data, information such as filename, filelength, and content-type </param> // <returns> </returns> UploadJsonResult UploadTempMedia (string accessToken, UploadMediaFileType type, string file );

According to the instructions on the official interface, we need to upload a file and specify its TYPE.

The Code is as follows.

        public UploadJsonResult UploadTempMedia(string accessToken, UploadMediaFileType type, string file)        {            string url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", accessToken, type.ToString());            UploadJsonResult result = JsonHelper<UploadJsonResult>.PostFile(url, file);            return result;        }

Among them, the PostFile of the JsonHelper class is to send a file stream. We can see its implementation ideas as follows.

/// <Summary> /// submit the file and parse the returned result /// </summary> /// <param name = "url"> url of the submitted file data </param> /// <param name = "file"> file address </param> /// <returns> </returns> public static T PostFile (string url, string file, NameValueCollection nvc = null) {HttpHelper helper = new HttpHelper (); string content = helper. postStream (url, new string [] {file}, nvc); VerifyErrorCode (content); T result = JsonConvert. deserializeObject <T> (content); return result ;}

The above code is mainly to POST a file stream and obtain the response result string content. Then we analyze whether there is any error code. If not, we can resolve the string result to the corresponding object.

The object class information of the returned result is defined as follows.

/// <Summary> /// upload the returned results of the multimedia file /// </summary> public class UploadJsonResult: baseJsonResult {// <summary> // media file types, including image, voice, video, and thumb, it is mainly used for thumbnails of video and music formats) /// </summary> public UploadMediaFileType {get; set ;}/// <summary> // after a media file is uploaded, the unique identifier at the time of obtaining. // </summary> public string media_id {get; set ;} /// <summary> /// Media File Upload timestamp /// </summary> public long created_at {get; set ;}}

The instance code for calling this interface is as follows.

Private void btnUpload_Click (object sender, EventArgs e) {string file = FileDialogHelper. OpenImage (false); if (! String. IsNullOrEmpty (file) {IMediaApi mediaBLL = new MediaApi (); UploadJsonResult result = mediaBLL. UploadTempMedia (token, UploadMediaFileType. image, file); if (result! = Null) {this. image_mediaId = result. media_id; Console. writeLine ("{0} {1}", result. media_id, result. created_at);} else {Console. writeLine ("failed to upload file ");}}}

 

2) Get the temporary clip file

Uploading a file is to upload a file stream and obtain the corresponding returned results. It is mainly a media_Id content, while obtaining the material file is a inverse process, you can use media_id to obtain the process of saving a file stream to a local device.

The official definition of the interface for obtaining temporary files is as follows.

API call request description

Http Request Method: GET, https call https://api.weixin.qq.com/cgi-bin/media/get? Access_token = ACCESS_TOKEN & media_id = MEDIA_ID request example (the example is to get a multimedia file through the curl command) curl-I-G "https://api.weixin.qq.com/cgi-bin/media/get? Access_token = ACCESS_TOKEN & media_id = MEDIA_ID"

For obtaining temporary files, we define the interface as follows.

/// <Summary> /// obtain temporary materials /// </summary> /// <param name = "accessToken"> call interface creden< </param> /// <param name = "mediaId"> media file ID </param> // <param name = "stream"> </param> Stream GetTempMedia (string accessToken, string mediaId, ref string fileName );

When we get the file stream, we also return a file name parameter (but we usually cannot get the file name ).

Its implementation code is as follows. The main logic is to parse the returned results and obtain the returned file stream.

/// <Summary> /// obtain temporary materials /// </summary> /// <param name = "accessToken"> call interface creden< </param> /// <param name = "mediaId"> media file ID </param> // <param name = "stream"> </param> public Stream GetTempMedia (string accessToken, string mediaId, ref string fileName) {string url = string. format ("http://file.api.weixin.qq.com/cgi-bin/media/get? Access_token = {0} & media_id = {1} ", accessToken, mediaId); HttpHelper helper = new HttpHelper (); Stream stream = helper. getStream (url, ref fileName, null); return stream ;}

The example code for getting the clip file is as follows.

Private void btnDownload_Click (object sender, EventArgs e) {if (! String. isNullOrEmpty (image_mediaId) {IMediaApi mediaBLL = new MediaApi (); string fileName = ""; Stream stream = mediaBLL. getTempMedia (token, image_mediaId, ref fileName); if (stream! = Null) {string filePath = Path. combine (System. appDomain. currentDomain. baseDirectory, fileName); using (var fileStream = File. create (filePath) {byte [] buffer = new byte [1024]; int bytesRead = 0; while (bytesRead = stream. read (buffer, 0, buffer. length ))! = 0) {fileStream. write (buffer, 0, bytesRead);} fileStream. flush ();} stream. close ();} Console. writeLine ("download File:" + (File. exists (fileName )? "Successful": "failed "));}}

 

3. definition and implementation of management interfaces for permanent materials

According to the description of the official interface, we can define three new permanent material interfaces: New graphic materials, other types of permanent materials, and video materials.

1) add permanent graphic materials

API call request description

Http Request Method: POSThttps: // api.weixin.qq.com/cgi-bin/material/add_news? Access_token = ACCESS_TOKEN

Call example

{"Articles": [{"title": TITLE, "thumb_media_id": THUMB_MEDIA_ID, "author": AUTHOR, "digest": DIGEST, "show_cover_pic": SHOW_COVER_PIC (0/1 ), "content": CONTENT, "content_source_url": CONTENT_SOURCE_URL}
2) add other types of permanent materials

API call request description

The POST form is used to call the interface. The Form id is media and contains the content of the materials to be uploaded, including filename, filelength, and content-type. Please note: The image materials will go to the default group in the material management module of the official website of the public platform.

Http Request Method: POSThttp: // api.weixin.qq.com/cgi-bin/material/add_material? Access_token = ACCESS_TOKEN call example (use the curl command to add another type of permanent material in FORM mode): curl-F media=@test.jpg "http://file.api.weixin.qq.com/cgi-bin/material/add_material? Access_token = ACCESS_TOKEN"
3) add permanent video clips

When uploading a video clip, you need to POST another form with the id of description, which contains the description of the clip. The content format is JSON. The format is as follows:

{  "title":VIDEO_TITLE,  "introduction":INTRODUCTION}

Call example for adding permanent video clips:

curl "http://file.api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN" -F media=@media.file -F  description='{"title":VIDEO_TITLE, "introduction":INTRODUCTION}'

 

According to the preceding instructions, the interface code for creating permanent graphic materials is as follows.

/// <Summary> /// add permanent graphic materials /// </summary> /// <param name = "accessToken"> call interface creden< </param> // /<param name = "newsList"> text message group </param> // <returns> </returns> MaterialResult UploadMaterialNews (string accessToken, list <NewsUploadJson> newsList );

Other permanent material interfaces are defined as follows:

/// <Summary> /// add other types of permanent materials (image, voice, and thumb )) /// </summary> /// <param name = "accessToken"> call interface creden< </param> /// <param name = "type"> media file type, images, voice, video, and thumb) </param> /// <param name = "file"> ID of a media file in form-data, information such as filename, filelength, and content-type </param> // <returns> </returns> MaterialResult UploadMaterialMedia (string accessToken, UploadMediaFileType type, string file );

The following is an interface for defining permanent video clips:

/// <Summary> /// when uploading a video clip, you need to POST another form with the id of description, which contains the description of the clip. The content format is JSON. /// </summary> /// <param name = "accessToken"> call interface creden< </param> /// <param name = "file"> form-data media File ID, information such as filename, filelength, and content-type </param> // <param name = "title"> video title </param> /// <param name = "introduction "> video description </param> /// <returns> </returns> MaterialResult UploadMaterialVideo (string accessToken, string file, string title, string introduction );

These interfaces do not have much difficulty, but in the interface discussion group, many people are always unsuccessful in uploading permanent materials. They think it may be a problem of the API itself, I still passed the test and saw the corresponding material information on the server. Let's take a look at the implementation code of the interface for uploading other types of materials.

/// <Summary> /// add other types of permanent materials (image, voice, and thumb )) /// </summary> /// <param name = "accessToken"> call interface creden< </param> /// <param name = "type"> media file type, images, voice, video, and thumb) </param> /// <param name = "file"> ID of a media file in form-data, information such as filename, filelength, and content-type </param> // <returns> </returns> public MaterialResult UploadMaterialMedia (string accessToken, UploadMediaFileType type, string file) {string url = string. format ("Http://api.weixin.qq.com/Cgi-bin/material/add_material? Access_token = {0} & type = {1} ", accessToken, type. toString (); MaterialResult result = JsonHelper <MaterialResult>. postFile (url, file); return result ;}

Note that this URL is http rather than https, which is a bit special.

In addition, when we use the POST file stream, the content of the HttpWebRequest object must be set, mainly because it must be consistent with the defined media. The following is part of the PostStream code in the HttpHelper helper class for your reference.

You can view the permanent material upload result in the public account background. The specific interface is as follows.

For the permanent material interface, we can also update, delete, and retrieve permanent materials as required by the API, as well as obtain the total number of materials and the list of graphic materials, most of the operations are similar and do not need to be listed one by one. We hope to give you a better understanding of and make good use of the material management interface of the public account to achieve richer data management.

If you are interested in this series of C # development portals and applications, you can follow my other articles as follows:

C # development portal and application (26)-Material Management of Public Accounts

C # development portal and application (25)-enterprise account Client Management Function

C # development portal and application (24)-store shelf Information Management

C # development portal and application (23)-packaging and testing of the store product management interface

C # development portal and application (22)-Development and Use of stores

C # development portal and application (21)-receiving, processing, and decryption of enterprise numbers and events

C # development portal and application (20)-menu management of enterprise number

C # development portal and application (19)-sending of enterprise numbers (text, images, files, voice, video, text messages, etc)

C # development portal and application (18)-member management for enterprise address book management and development

C # development portal and application (17)-department management for enterprise address book management and development

C # development portal and application (16)-enterprise number configuration and use

C # development portal and application (15)-added the scan, image sending, and geographic location functions in the menu

C # development portal and application (14)-use redirection in the menu to obtain user data

C # development portal and application (13)-use geographic location Extension

C # development portal and application (12)-use voice processing

C # development portal and application (11)-menu presentation

C # development portal and application (10) -- synchronize user group information in the management system

C # development portal and application (9)-portal menu management and submission to server

C # development portal and application (8)-portal application management system function Introduction

C # development portal and application (7)-Multi-customer service functions and development integration

C # development portal and application (6)-portal menu management operations

C # development portal and application (5) -- User Group Information Management

C # development portal and application (4) -- Focus on the user list and detailed information management

C # development portal and application (3) -- Response to text messages and text messages

C # development portal and application (2) -- Message Processing and response

C # development portal and application (1) -- getting started with Interfaces

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.