C#开发微信公众号教程

两种类型:

1、开发不通过开发者web服务中转,直接通过HTTP请求来进行发送客服消息,此种只要软件有外网可以请求微信服务器就可以,通过微信服务器可以直接把所要发送的信息,发送给某个用户。-----------开发一个winform应用程序就可以了。

2、是通过开发者的Web服务器,进行发送,此类型应用的类型为,客户在公众号里发信息,----->微信服务器------>开发者服务器,开发者服务器收到用户发的信息后,根据收到的信息进行相应的数据返回。此类型要建立web服务器,可以使用微软的IIS进行服务器搭建,并将搭建的服务器IP映射到外网里,可以通过花生壳或ngrok软件进行映射。-------创建asp.net网页,并发布到外网上。或者自己写一个webserve进行接收外网连接,利用asp.net IIS服务器相对来说比较简单些。***微信服务器访问asp.net开发的网页时,根据映射的网址会访问该网页,进行触发PageLoad事件,这和是否有页面显示没有关系,访问网页时会触发该网址

 

发送的客服消息接口调试

代码链接如下:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Weixin
{
    public partial class Form1 : Form
    {
        private string accessToken = string.Empty;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private string GetAccessToken(string appID,string appSecret)
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appID, appSecret);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            HttpWebResponse resopnse = request.GetResponse() as HttpWebResponse;
            Stream ioStream = resopnse.GetResponseStream();
            StreamReader sr = new StreamReader(ioStream, Encoding.UTF8);
            string result = sr.ReadToEnd();
            sr.Close();
            ioStream.Close();
            resopnse.Close();
            Log(result);
            return result;
        }

        private void  SendMsgToUser (string msg)
        {
            //string accessToken="29_D21kEvOnhSa1QKOXXJOqtoH1UYP5fumXj44pFknfhlktk4ZBYrDUEOLuARqm6_ACH6YWxBc2PWJaDCEDWMEN6RP1NpiepdQGhFv7QV2y25JdoBrO4zufW8aiHVYMNIeADAVWR";
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}", accessToken);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] payLoad;
            payLoad = System.Text.Encoding.UTF8.GetBytes(msg);
            request.ContentLength = payLoad.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(payLoad, 0, payLoad.Length);
            writer.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamReceive = response.GetResponseStream();
            Encoding encoding = Encoding.GetEncoding("UTF-8");
            StreamReader streamReader = new StreamReader(streamReceive, encoding);
            string result = streamReader.ReadToEnd();
            textBox1.Text = result;
            streamReader.Close();
            response.Close();
            streamReceive.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string data = textBox2.Text;
            var a = new
            {
                touser = "om48Awf7juJ0S3LKE4_4VUlDlAxE",   //获取用的openID,来针对哪个用户进行发送
                msgtype = "text",
                text = new { content = data }

            };
            string msg = JsonConvert.SerializeObject(a, Formatting.Indented);
            //string msg="{\"touser\":\"om48Awf7juJ0S3LKE4_4VUlDlAxE\",\"msgtype\":\"text\",\"text\":{\"content\":\"测试工业设备状态\"}}";
            SendMsgToUser(msg);
        }

        public void Log(string msg)
        {
            using (StreamWriter sw = new StreamWriter(@"Log\1.txt", true))
            {
                sw.WriteLine(msg);
            }
        }

        private void btnGetAccessToken_Click(object sender, EventArgs e)
        {
            string appID = "wx9bfd2290b6ca0a7a";
            string appSecret = "35edfab5b4d18fe929f96d33a291f4dc";
            string data = GetAccessToken(appID, appSecret);
            AccessTokenResult accessTokenResult = JsonConvert.DeserializeObject<AccessTokenResult>(data);
            textBox1.Text = accessTokenResult.access_token;
            accessToken = accessTokenResult.access_token;
        }
    }
    public class AccessTokenResult 
    {
        public string access_token { get; set; }
        public string expires_in { get; set; }
    }
  


}

2、开发asp.net web程序,首先要进行IISweb服务器配置,自行百度win10下IIS服务器配置方法。配置好之后将localhost 80端口映射到外网上,并将该网址配置到web配置页面上,如下图。将web程序进行发布到网络上。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace WebApplication11
{
    public partial class Index : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            Log(Request.HttpMethod );
            Console.WriteLine("deec");
            if (Request .HttpMethod =="GET")
            {
                string echostr=Request .QueryString ["echostr"];
                Log (echostr);
                //验证服务器有效性
                Response.Write(echostr);
                Response.End();
                
            }
            else if (Request .HttpMethod =="POST")
            {
         
                Log(Request.InputStream.Length.ToString());
                Console.WriteLine("deec");


            }

            System.IO.Stream s = Request.InputStream;
            int count = 0;
            byte[] buffer = new byte[s.Length];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, buffer.Length)) > 0)
            {
                builder.Append(Request.ContentEncoding.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();
            Log(builder.ToString());
            if (builder .ToString ().Contains ("全"))
            {
                var a = new
                {
                    touser = "om48Awf7juJ0S3LKE4_4VUlDlAxE",
                    msgtype = "text",
                    text = new { content = "自动发送" }

                };
                string msg = JsonConvert.SerializeObject(a, Formatting.Indented);
                SendMsgToUser(msg);
            }

        }
        public void Log(string msg)
        {
            using (StreamWriter sw = new StreamWriter(@"D:\www\Log\1.txt",true))
            {
                sw.WriteLine(msg);
            }
        }
        private void SendMsgToUser(string msg)
        {
            string accessToken = "29_1viONwph6bWypwb8zqD7RnaKTnIL34BIsNg3F_EnZQd1Hygf9irnXDgz8KNXAaTqfLPDMIXu1ASqDxZ40w5UQ_1VY3Oty5t7fn2AiCLnDBQ_rpyWIbORhZvWIOG11q4CUC6GRky4soHYN65YVUCiABAHGO";
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}", accessToken);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] payLoad;
            payLoad = System.Text.Encoding.UTF8.GetBytes(msg);
            request.ContentLength = payLoad.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(payLoad, 0, payLoad.Length);
            writer.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamReceive = response.GetResponseStream();
            Encoding encoding = Encoding.GetEncoding("UTF-8");
            StreamReader streamReader = new StreamReader(streamReceive, encoding);
            string result = streamReader.ReadToEnd();
            //textBox1.Text = result;
            streamReader.Close();
            response.Close();
            streamReceive.Close();
        }
    }


}

参考文章链接:

https://blog.csdn.net/qq_31583959/article/details/52087987
https://blog.csdn.net/luvian_luvian/article/details/88052220
https://blog.csdn.net/mc0csdn02015/article/details/82080066
https://blog.csdn.net/weixin_33801856/article/details/85689554
https://blog.csdn.net/qq285679784/article/details/102834215
https://baijiahao.baidu.com/s?id=1633149193665169425&wfr=spider&for=pc
https://blog.csdn.net/woai671/article/details/45666665
https://blog.csdn.net/qq_31583959/article/details/52087987
https://blog.csdn.net/m0_38004177/article/details/86483456
https://jingyan.baidu.com/album/e4d08ffdb3fc090fd2f60d25.html?picindex=1

C#版的微信公众号开发SDK Senparc.Weixin.MP几个关键类介绍如下: Entities/Request*.cs 用于接收微信平台自动发送到服务器的实体(发送过来的是XML),包括文本、位置、图片三类 Entities/Response*.cs 用于反馈给发送人的信息实体(最终会转成XML),包括文本、新闻(图文)两类 Helpers/EntityHelper.cs 用于实体和XML之间的转换(由于其中有许多需要特殊处理的字段和类型,这里不能简单用XML序列化) Helpers/MsgTypeHelper.cs 用于获取消息类型 CheckSignature.cs 验证请求合法性类 Enums.cs 各种枚举 RequestMessageFactory.cs 用于自动生成不同Request类型的实体,并作必要的数据填充 Senparc.Weixin.MP几个关键类及重要方法(按一般使用过程排序) 生成验证字符串:Senparc.Weixin.MP.CheckSignature.GetSignature(string timestamp, string nonce, string token = null),返回根据微信平台提供的数据,SHA1加密后的验证字符串(注意token必须跟公众平台的设置一直) 验证请求:Senparc.Weixin.MP.CheckSignature.Check(string signature, string timestamp, string nonce, string token = null),验证请求是否合法 获取请求实体:var requestMessage = Senparc.Weixin.MP.RequestMessageFactory.GetRequestEntity(XDocument doc); 根据不同请求的类型,自动生成可用于操作的实体(doc只需要用XDocument.Parse(xmlString)就能生成),requestMessage.MsgType就是请求枚举类型。 进行判断及各类操作。 根据需要,创建响应类型的实体,如:var responseMessage = ResponseMessageBase.CreateFromRequestMessage(requestMessage, ResponseMsgType.Text) as ResponseMessageText; 即可返回文本类型信息。 由于目前微信只接受XML的返回数据,所以在返回之前还需要做一次转换:XDocument responseDoc = Senparc.Weixin.MP.Helpers.EntityHelper.ConvertEntityToXml(responseMessage); var xmlString =responseDoc.ToString();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值