搜索
首页微信小程序微信开发微信开发之微信发送消息

微信开发之微信发送消息

Mar 09, 2017 pm 03:47 PM
微信开发

本内容为微信开发之微信发送消息 

1,首先,获取开发者测试账号(申请),会根据当前扫码提供的账号生成测试账号: 链接地址:http://mp.weixin.qq.com/wiki/home/index.html

微信开发之微信发送消息

 

  这时候可以获取到测试用的appid和appsecrept,然后调用获取接口调用凭证 接口获取access_token;

2,下面说信息发送,模拟了单用户信息发送和多用户消息批量发送

  (1)基础方法,http方法    

/// <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;
        }

(2)模拟发送:  

/// <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);
        }

  (3)两个参数 模型: 

/// <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; }

    }

   (4)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}"/>
    <!--\微信接口-->

 3,测试使用涉及到  touser的这个参数,这个是需要发送的对象的  openID,这个很简单,在开发者文档(也就是上面的步骤二中,)获取

appid  和appsecrept的时候,当前这个页面下面有一个二维码,找几个人用微信扫扫就可以自动获取openID ,这时候将参数带入脚本模拟

post即可

  另外需要注意:文档中提示的  json 参数格式

  注意三:token有效时间为7200,俩小时,需要判断当前发送信息用户的token有效性,同时每天最大可请求次数为2000.

获取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

 

以上是微信开发之微信发送消息 的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版