Home > WeChat Applet > WeChat Development > WeChat development WeChat sends messages

WeChat development WeChat sends messages

高洛峰
Release: 2017-03-09 15:47:42
Original
1879 people have browsed it

This content is about WeChat sending messages developed by WeChat

1. First, obtain the developer test account (application). The test account will be generated based on the account provided by the current scan code: Link address: http:// mp.weixin.qq.com/wiki/home/index.html

微信开发之微信发送消息

At this time, you can get the appid and appsecret for testing, and then call Get the interface and call the credential interface to get the access_token;

2, let’s talk about information sending, which simulates single-user information sending and multi-user message batch sending

(1) Basic method, http method

/// <summary>
        ///      http  get/post 公用方法
        /// </summary>
        /// <param name="requestUrl">请求链接</param>
        /// <param name="requestJsonParams">请求参数值(如果是get方式此处为“”值,默认为 "")</param>
        /// <param name="requestMethod">请求方式  post or get</param>
        /// <returns></returns>
        public static string Request(this string requestUrl, string requestMethod, string requestJsonParams = "")
        {
            string returnText = "";
            StreamReader streamReader = null;
            HttpWebRequest request = null;
            HttpWebResponse response = null;

            Encoding encoding = Encoding.UTF8;
            request = (HttpWebRequest)WebRequest.Create(requestUrl);
            request.Method = requestMethod;
            if (!string.IsNullOrEmpty(requestJsonParams) && requestMethod.ToLower() == "post")
            {
                byte[] buffer = encoding.GetBytes(requestJsonParams);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
            }

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                using (streamReader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("gb2312")))//utf-8
                {
                    returnText = streamReader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                returnText = ex.Message;
            }

            return returnText;
        }
Copy after login

(2) Simulation transmission:

/// <summary>
        ///     发送微信信息(单用户发送)
        /// </summary>
        /// <param name="access_token">授权码(微信token)</param>
        /// <param name="messageInfo">发送信息模型</param>
        /// <returns></returns>
        public static string SendSingleMessage(WeChatParamEntity messageInfo, string access_token)
        {
            messageInfo.MsgType = string.IsNullOrEmpty(messageInfo.MsgType) ? "text" : messageInfo.MsgType;
            string jsonDataParams = messageInfo == null ? "" : JsonConvert.SerializeObject(new
            {
                touser = messageInfo.ToUser,
                msgtype = messageInfo.MsgType,
                text = new { content = messageInfo.Text }
            });
            string requestUrl = string.Format(Consts.URL_POSTSINGLETEXTMESSAGE, access_token);
            return requestUrl.Request("POST", jsonDataParams);
        }
        /// <summary>
        ///     发送微信信息(多用户批量发送)
        /// </summary>
        /// <param name="access_token">授权码(微信token)</param>
        /// <param name="messageInfo">发送信息模型</param>
        /// <returns></returns>
        public static string SendMessages(WeChatParamsEntity messageInfo, string access_token)
        {
            messageInfo.MsgType = string.IsNullOrEmpty(messageInfo.MsgType) ? "text" : messageInfo.MsgType;
            string jsonDataParams = messageInfo == null ? "" : JsonConvert.SerializeObject(new
            {
                touser = messageInfo.ToUser,
                msgtype = messageInfo.MsgType,
                text = new { content = messageInfo.Text }
            });
            string requestUrl = string.Format(Consts.URL_POSTTEXTMESSAGES, access_token);
            return requestUrl.Request("POST", jsonDataParams);
        }
Copy after login

(3) Two parameter model:

/// <summary>
    ///     微信 发送信息 参数实体模型
    /// </summary>
    public class WeChatParamEntity
    {
        /// <summary>
        ///     普通用户openid
        /// </summary>
        public string ToUser { get; set; }
        /// <summary>
        ///     传输的文件类型(text,image, and so on)
        /// </summary>
        public string MsgType { get; set; } = "text";
        /// <summary>
        ///     传输文本内容
        /// </summary>
        public string Text { get; set; }

    }

    /// <summary>
    ///     微信 发送信息 参数实体模型
    /// </summary>
    public class WeChatParamsEntity
    {
        /// <summary>
        ///     普通用户openid
        /// </summary>
        public string[] ToUser { get; set; }
        /// <summary>
        ///     传输的文件类型(text,image, and so on)
        /// </summary>
        public string MsgType { get; set; } = "text";
        /// <summary>
        ///     传输文本内容
        /// </summary>
        public string Text { get; set; }

    }
Copy after login

  (4) Link in web.config

 

<!--微信接口-->

    <add key="appid" value="wx123456789021"/>
    <add key="appSecret" value="adasdsadasdasdsadasdsaqweqw"/>
    <add key="getAccessTokenUrl" value="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&amp;appid={0}&amp;secret={1}"/>
    <!--单用户信息发送-->
    <add key="postSingleTextMessageUrl" value="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}"/>
    <!--多用户批量发送-->
    <add key="postTextMessagesUrl" value="https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={0}"/>
    <!--\微信接口-->
Copy after login

3. The test uses this parameter involving touser. This is the openID of the object that needs to be sent. This is very simple. Get the

appid and appsecret in the developer documentation (that is, step 2 above). At that time, there is a QR code under the current page. Find a few people to scan it with WeChat to automatically obtain the openID. At this time, enter the parameters into the script to simulate

post

In addition Note: The json parameter format prompted in the document

Note 3: The token is valid for 7200, two hours. It is necessary to determine the validity of the token of the user currently sending the information. At the same time, the maximum number of requests per day is 2000.

Get token:

#region 获取token,并验证token过期时间

        public static string GetAccessToken(string appid, string appSecret)
        {
            string token = "";
            string requestUrl = string.Format(ConfigBLL.URL_GETACCESSTOKEN, appid, appSecret);
            string requestResult = WebAPITransfer.Request(requestUrl, "GET", "");

            CommonBLL.DebugLog(requestResult, "AccessToken-token-Params");
            string[] strArray = requestResult.Split(',');
            token = strArray[0].Split(':')[1].Replace("\"", "");

            return token;
        }

        #endregion
Copy after login

The above is the detailed content of WeChat development WeChat sends messages. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template