当前位置: 移动技术网 > IT编程>开发语言>.net > .net开发微信公众平台实例教程

.net开发微信公众平台实例教程

2017年12月12日  | 移动技术网IT编程  | 我要评论

autocad2008破解版,黑帮高中2,公关礼仪视频

本文实例讲述了.net开发微信公众平台的方法。分享给大家供大家参考。具体实现方法如下:

一、说明:

公众平台信息接口为开发者提供了一种新的消息处理方式,只有申请成为开发者后,你才能使用公众平台的开发功能,在这里你需要填写一个url和一个token,这两项信息也需要你拥有自己的服务器(外网服务器)资源,其中的token可由开发者任意填写,url即是接口配置信息的链接地址,在本文中我采用的是创建一个简易网站的方式,在其中的一个页面的后台程序中配置相关的接口信息,然后发布到外网服务器上,最后可以访问到这个页面的链接地址即是这里应该填写的url。

二、接口配置过程:

1.网址接入-校验签名:

复制代码 代码如下:
const string token = "aka";//定义一个局部变量不可以被修改,这里定义的变量要与接口配置信息中填写的token一致
protected void page_load(object sender, eventargs e)
{
        string poststr = "";
        valid();//校验签名,当填入的信息提交之后页面有提示“你已成功成为公众平台开发者,可以使用公众平台的开发功能”这个的时候,接下来你就需要注释掉这个校验的方法,使得后面的消息回复得以正常运作
        if (request.httpmethod.tolower() == "post")//当普通微信用户向公众账号发消息时,微信服务器将post该消息到填写的url上
        {
            poststr = postinput();
            if (string.isnullorempty(poststr) == false)
            {
                //writelog(poststr,server);//计入日记
                responsemsg(poststr);
            }
        }
}
private void valid()
{
        string echostr = request.querystring["echostr"].tostring();
        if (checksignature())
        {
            if (!string.isnullorempty(echostr))
            {
                response.write(echostr);
                response.end();
            }
        }
}

复制代码 代码如下:
/// <summary>
/// 验证微信签名
/// </summary>
/// <returns></returns>
private bool checksignature()
{
        string signature = request.querystring["signature"].tostring();
        string timestamp = request.querystring["timestamp"].tostring();
        string nonce = request.querystring["nonce"].tostring();
        string[] arrtmp = { token, timestamp, nonce };
        array.sort(arrtmp);//字典排序
        string tmpstr = string.join("", arrtmp);
        tmpstr = formsauthentication.hashpasswordforstoringinconfigfile(tmpstr, "sha1");//对该字符串进行sha1加密
        tmpstr = tmpstr.tolower();//对字符串中的字母部分进行小写转换,非字母字符不作处理
        //writelog(tmpstr, server);//计入日志
        if (tmpstr == signature)//开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。开发者通过检验signature对请求进行校验,若确认此次get请求来自微信服务器,请原样返回echostr参数内容,则接入生效,否则接入失败
        {
            return true;
        }
        else
            return false;
}

/// <summary>
/// 获取post返回来的数据
/// </summary>
/// <returns></returns>
private string postinput()
{
        stream s = system.web.httpcontext.current.request.inputstream;
        byte[] b = new byte[s.length];
        s.read(b, 0, (int)s.length);
        return encoding.utf8.getstring(b);
}

/// <summary>
///返回微信信息结果
/// </summary>
/// <param name="weixinxml"></param>
private void responsemsg(string weixinxml)
{
        try
        {
            xmldocument doc = new xmldocument();
            doc.loadxml(weixinxml);//读取xml字符串
            xmlelement rootelement = doc.documentelement;

            xmlnode msgtype = rootelement.selectsinglenode("msgtype");//获取字符串中的消息类型

            string resxml = "";
            if (msgtype.innertext == "text")//如果消息类型为文本消息
            {
                var model = new
                {
                    tousername = rootelement.selectsinglenode("tousername").innertext,
                    fromusername = rootelement.selectsinglenode("fromusername").innertext,
                    createtime = rootelement.selectsinglenode("createtime").innertext,
                    msgtype = msgtype.innertext,
                    content = rootelement.selectsinglenode("content").innertext,
                    msgid = rootelement.selectsinglenode("msgid").innertext
                };
                resxml += "<xml><tousername><![cdata[" + model.fromusername + "]]></tousername><fromusername><![cdata[" + model.tousername + "]]></fromusername><createtime>" + convertdatetimeint(datetime.now) + "</createtime>";
                if (!string.isnullorempty(model.content))//如果接收到消息
                {
                    if (model.content.contains(" 你好") || model.content.contains(" 好") || model.content.contains("hi") || model.content.contains("hello"))// 你好
                    {
                        resxml += "<msgtype><![cdata[text]]></msgtype><content><![cdata[你好,有事请留言,偶会及时回复你的。]]></content><funcflag>0</funcflag></xml>";
                    }

                 }

                 else//没有接收到消息
                {
                    resxml += "<msgtype><![cdata[text]]></msgtype><content><![cdata[亲,感谢您对我的关注,有事请留言。]]></content><funcflag>0</funcflag></xml>";
                }

                response.write(resxml);
            }
            if (msgtype.innertext == "image")//如果消息类型为图片消息
            {
                var model = new
                {
                    tousername = rootelement.selectsinglenode("tousername").innertext,
                    fromusername = rootelement.selectsinglenode("fromusername").innertext,
                    createtime = rootelement.selectsinglenode("createtime").innertext,
                    msgtype = msgtype.innertext,
                    picurl = rootelement.selectsinglenode("picurl").innertext,
                    msgid = rootelement.selectsinglenode("msgid").innertext
                };
                resxml += "<xml><tousername><![cdata[" + model.fromusername + "]]></tousername><fromusername><![cdata[" + model.tousername + "]]></fromusername><createtime>" + convertdatetimeint(datetime.now) + "</createtime><msgtype><![cdata[news]]></msgtype><articlecount>1</articlecount><articles><item><title><![cdata[欢迎您的光临!]]></title><description><![cdata[非常感谢您的关注!]]></description><picurl><![cdata[http://...jpg]]></picurl><url><![cdata[http://www.baidu.com/]]></url></item></articles><funcflag>0</funcflag></xml>";
                response.write(resxml);
            }
            else//如果是其余的消息类型
            {
                var model = new
                {
                    tousername = rootelement.selectsinglenode("tousername").innertext,
                    fromusername = rootelement.selectsinglenode("fromusername").innertext,
                    createtime = rootelement.selectsinglenode("createtime").innertext,
                };
                resxml += "<xml><tousername><![cdata[" + model.fromusername + "]]></tousername><fromusername><![cdata[" + model.tousername + "]]></fromusername><createtime>" + convertdatetimeint(datetime.now) + "</createtime><msgtype><![cdata[text]]></msgtype><content><![cdata[亲,感谢您对我的关注,有事请留言,我会及时回复你的哦。]]></content><funcflag>0</funcflag></xml>";
                response.write(resxml);
            }
        }
        catch (exception ex)
        {
            throw ex;
        }
        response.end();

}
/// <summary>
/// datetime转换成unixtime
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
private int convertdatetimeint(system.datetime time)
{
        system.datetime starttime = timezone.currenttimezone.tolocaltime(new system.datetime(1970, 1, 1));
        return (int)(time - starttime).totalseconds;
}
/// <summary>
/// 写日志(用于跟踪),可以将想打印出的内容计入一个文本文件里面,便于测试
/// </summary>
public static void writelog(string strmemo, httpserverutility server)
{
        string filename = server.mappath("/logs/log.txt");//在网站项目中建立一个文件夹命名logs(然后在文件夹中随便建立一个web页面文件,避免网站在发布到服务器之后看不到预定文件)
        if (!directory.exists(server.mappath("//logs//")))
            directory.createdirectory("//logs//");
        streamwriter sr = null;
        try
        {
            if (!file.exists(filename))
            {
                sr = file.createtext(filename);
            }
            else
            {
                sr = file.appendtext(filename);
            }
            sr.writeline(strmemo);
        }
        catch
        {
        }
        finally
        {
            if (sr != null)
                sr.close();
        }
}

希望本文所述对大家的.net程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网