微信通过openID发送消息/后台post、get提交并接收数据 C# .NET 配置404,500等错误信息 连接字符串

控制器:下面是post发送消息(微信不支持从前台发送数据,之前试过,报错,需要跨域,跨域的问题解决后还不行,最后发现之后后端提交

WXApi类:
#region 验证Token是否过期
        /// <summary>
        ///  验证Token是否过期
        ///</summary>
        public static bool TokenExpired(string access_token)
        {
            string jsonStr = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", access_token));
            if (Tools.GetJsonValue(jsonStr, "errcode") == "42001")
            {
                return true;
            }
            return false;
        }
        #endregion
        #region 获取Token
        /// <summary>
        ///  获取Token
        /// </summary>
        public static string GetToken(string appid, string secret)
        {
            string strJson = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret));
            return Tools.GetJsonValue(strJson, "access_token");
        }
        #endregion


Tools类:
 #region 获取Json字符串某节点的值
        /// <summary>
        /// /// 获取Json字符串某节点的值
        /// /// </summary>
        public static string GetJsonValue(string jsonStr, string key)
        {
            string result = string.Empty; if (!string.IsNullOrEmpty(jsonStr))
            {
                key = "\"" + key.Trim(‘"‘) + "\""; int index = jsonStr.IndexOf(key) + key.Length + 1;
                if (index > key.Length + 1)
                {
                    //先截逗号,若是最后一个,截“}”号,取最小值
                    int end = jsonStr.IndexOf(‘,‘, index); if (end == -1)
                    {
                        end = jsonStr.IndexOf(‘}‘, index);
                    }
                    result = jsonStr.Substring(index, end - index);
                    result = result.Trim(new char[] { ‘"‘, ‘ ‘, ‘\‘‘ }); //过滤引号或空格
                }
            }
            return result;
        }
        #endregion

HttpRequestUtil类:
 #region 请求Url,不发送数据
        /// <summary>
        /// 请求Url,不发送数据
        /// </summary>
        public static string RequestUrl(string url)
        {
            return RequestUrl(url, "POST");
        }
        #endregion
        #region 请求Url,不发送数据
        /// <summary>
        /// 请求Url,不发送数据
        /// </summary>
        public static string RequestUrl(string url, string method)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = method;
            request.ContentType = "text/html";
            //request.GetRequestStream()
            //request.
            request.Headers.Add("charset", "utf-8");  //发送请求并获取相应回应数据
            Stream postStream = request.GetRequestStream();
            //postStream.Write(,0,bytearra)
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;//直到request.GetResponse()程序才开始向目标网页发送Post请求
            //Stream responseStream =
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);//返回结果网页(html)代码
            string content = sr.ReadToEnd();
            return content;
        }
        #endregion
        

下面是会返回错误44002的:原因是post数据未发送(没有提交数据),也是控制器中:
  #region 请求Url,不发送数据
        /// <summary>
        /// 请求Url,不发送数据
        /// </summary>
        public static string RequestUrl(string url)
        {
            return RequestUrl(url, "POST");
        }
        #endregion
        #region 请求Url,不发送数据
        /// <summary>
        /// 请求Url,不发送数据
        /// </summary>
        public static string RequestUrl(string url, string method)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = method;
            request.ContentType = "textml";
            request.Headers.Add("charset", "utf-8");  //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
            //返回结果网页(html)代码
            string content = sr.ReadToEnd();
            return content;
        }
        #endregion

)
 #region
        public string send(string openida, string senddata)
        {
            string posturl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + WXApi.GetToken(appID, appsecret);//发送地址
            string postData = "{\"touser\":\"" + openida + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + senddata + "\"}}";//发送消息的字符串 openida为openid,senddata为发送内容
            return GetPage(posturl, postData);//以post的形式发送出去
        }
        #endregion
        #region
        public string GetPage(string posturl, string postData)///向微信服务器发送post请求(主要是发送消息)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";//post的形式
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页(html)代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                //Response.Write(err);
                //return string.Empty;
                return err;
            }
        }
        #endregion

获取AppID和:appsecret ,(在控制器上面写上)
     public static readonly string appID = ConfigurationManager.AppSettings["appID"];
        public static readonly string appsecret = ConfigurationManager.AppSettings["appsecret"];
web.config中需要写入下面信息:
 <appSettings>
    <add key="appID" value="wxf39b0be4b27f0016" />
    <add key="appsecret" value="667b57fe3f9126b4c0960b1300c858db" />
 </appSettings>

C# .NET 配置404,500等错误信息

<customErrors mode="On" defaultRedirect="viewAll.html"><!--所有的错误显示页-->
     <error statusCode="403" redirect="view403.html" /><!--针对403的错误页-->
     <error statusCode="404" redirect="view404.html" /><!---针对404的错误页-->    <error statusCode="500" redirect="view500.html  /"><!--针对500的错误页-->
</customErrors>

连接字符串

<connectionStrings>
    <add name="ConnectionStrings" connectionString="Data Source=192.168.3.2;port=3306;Initial Catalog=tsyw;user id=root;password=123456;Charset=utf8"     providerName="MySql.Data.MySqlClient" />
    <add name="ConnectionStrings" connectionString="Data Source=192.168.3.2;Initial Catalog=TSYW;User ID=sa;Password=AAbb123456;Persist Security Info     =True;" providerName="System.Data.SqlClient" />
  <add name="ConnectionStrings" connectionString="data source=X450V-PC;initial catalog=TSYW;integrated security=True;MultipleActiveResultSets=True;    App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>

原文地址:https://www.cnblogs.com/cjm123/p/8695805.html

时间: 2024-12-13 09:20:24

微信通过openID发送消息/后台post、get提交并接收数据 C# .NET 配置404,500等错误信息 连接字符串的相关文章

微信企业号开发—发送消息

开始回调模式后我们就要实现聊天功能了.平时使用微信聊天可以发送文本消息.语音.图片.视频等,这里只实现了其中的一些功能和大家分享. 一.与微信企业号建立连接 1.企业应用调用企业号提供的接口,管理或查询企业号后台所管理的资源.或给成员发送消息等,以下称主动调用模式. 2.企业号把用户发送的消息或用户触发的事件推送给企业应用,由企业应用处理,以下称回调模式. 3.用户在微信中阅读企业应用下发的H5页面,该页面可以调用微信提供的原生接口,使用微信开放的终端能力,以下称JSAPI模式. 这是微信企业号

微信公众号发送消息之发送客服消息基类封装

当用户主动发消息给公众号的时候(包括发送信息.点击自定义菜单.订阅事件.扫描二维码事件.支付成功事件.用户维权),微信将会把消息数据推送给开发者,开发者在一段时间内(目前修改为48小时)可以调用客服消息接口,通过POST一个JSON数据包来发送消息给普通用户,在48小时内不限制发送次数.此接口主要用于客服等有人工消息处理环节的功能,方便开发者为用户提供更加优质的服务. http请求方式: POST https://api.weixin.qq.com/cgi-bin/message/custom/

Python 微信公众号发送消息

1. 公众号测试地址 https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index 2. 代码 # pip3 install requests import requests import json def get_access_token(): """ 获取微信全局接口的凭证(默认有效期俩个小时) 如果不每天请求次数过多, 通过设置缓存即可 ""

python 微信企业号-回调模式接收微信端客户端发送消息并被动返回消息

说明:此代码用于接收手机微信端发送的消息 #-*- coding:utf-8 -*- from flask import Flask,request from WXBizMsgCrypt import WXBizMsgCrypt import xml.etree.cElementTree as ET import sys app = Flask(__name__) @app.route('/index',methods=['GET','POST']) def index():         s

公众号用户发送消息后台PHP回复没有反应的解决办法

1.问题:微信公众平台官方提供下载的示例代码中,使用$postStr =$GLOBALS["HTTP_RAW_POST_DATA"];来获取微信服务器推送的消息数据.但是有的开发者在使用的过程中发现无法接收到信息(例如使用了新浪云). 2.原因:其根本原因在于接口配置的url所在服务器设置了register_globals=off. 从PHP4.2.0版本开始,php.ini设置选项中register_globals的默认值变成了off. 3.解决方法:1)修改php.ini设置,将r

微信小程序如何把后台返回的多条json数据的时间戳转换为时间放到页面上 (微信小程序 时间戳转换为时间)

小程序端 在utils文件夹下的util.js写入 //时间戳转换时间   function toDate(number){   var n=number * 1000;   var date = new Date(n);   var Y = date.getFullYear() + '/';   var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '/';   var D = date

axios发送post请求,如何提交表单数据?

var app = new Vue({ el: "#register", data: { registerUrl: "/KindlePocket/bindingData" newUserInfo: { userName:'n', phone:'13', email:'12', emailPwd:'22', kindleEmail:'asd' } }, methods: { register: function() { axios.post(this.register

shell使用微信公众号发送模板消息

1.配置微信公众号 由于没有认证的公众号,只能通过自己申请的个人订阅号(可以自行申请),并到开发者工具中开通公众平台测试帐号实现该功能. 1.获取测试公众号appID和appsecret *2.关注测试号二维码获取用户openid 3.新增模板获取模板ID 得到模板id: OA0PX8pqc2X7t_y05y5GxZ8LutBpu341FIYSeQOkno 2.通过脚本实现消息发送 #!/bin/sh # 微信消息发送脚本 zhutw #全局配置-- #微信公众号appID appID=wxe1

微信公众平台 自动回复消息

含有4个类 Wechat 消息处理Encrypt 消息加解密Encodexml xml处理WeixinEvent 返回数据处理 1 namespace app\common\logic\Wechat; 2 3 /** 4 * Class Weixin 获取服务器发送的消息并返回消息 5 * 6 * 包含 Encrypt AES加解密类 7 * 包含 Encodexml xml格式化类 8 */ 9 10 class Wechat 11 { 12 // 消息加解密类 13 protected $e