牛腩自己写的微信helper

自己写的微信helper, .net 下的,下载微信DEMO了直接在项目里面建立的文件:


using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Security;

////// 牛腩自己写的微信helper
/// https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
///namespace WxPayAPI
{
    public class NiunanWXHelper
    {

        ///根据日期取是星期几
        /// 
        /////////public static string GetXingQi_ALL(DateTime d)
        {
            string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            string week = Day[Convert.ToInt32(d.DayOfWeek.ToString("d"))].ToString();
            return week;
        }


        ////// 获取AccessToken,缓存中没有则重新取
        //////public string GetAccessToken()
        {

            if (HttpRuntime.Cache.Get("wx_accesstoken") == null)
            {

                try
                {
                    string appid = WxPayConfig.APPID;
                    string secret = WxPayConfig.APPSECRET;

                    //1. 获取AccessToken(有效期7200秒,开发者必须在自己的服务全局缓存access_token)
                    string url1 = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
                    string result = HttpService.Get(url1);
                    Log.Info(this.GetType().ToString(), "取微信accesstoken,远程返回:" + result);
                    JsonData jd = JsonMapper.ToObject(result);

                    string access_token = (string)jd["access_token"];
                    int expires_in = (int)jd["expires_in"];
                    HttpRuntime.Cache.Add("wx_accesstoken", access_token, null, DateTime.Now.AddSeconds(expires_in), Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
                    return access_token;
                }
                catch (Exception ex)
                {
                    Log.Error(this.GetType().ToString(), "取微信accesstoken出错【" + ex.Message + "】");
                    throw ex;
                }
            }
            else
            {
                return HttpRuntime.Cache.Get("wx_accesstoken").ToString();
            }
        }

        //////   返回使用微信JS-SDK接口的配置
        //    appId: @ViewBag.wx_appid, // 必填,企业号的唯一标识,此处填写企业号corpid
        //    timestamp: @ViewBag.wx_timestamp, // 必填,生成签名的时间戳
        //    nonceStr: @ViewBag.wx_noncestr, // 必填,生成签名的随机串
        //    signature: @ViewBag.wx_signature,// 必填,签名,见附录1
        //////public WxPayData GetJSSDKConfig()
        {
            string appid = WxPayConfig.APPID;
            string timestamp = WxPayApi.GenerateTimeStamp();
            string noncestr = WxPayApi.GenerateNonceStr();
            string signature = "";

            //签名算法  https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
            //1. 获取AccessToken(有效期7200秒,开发者必须在自己的服务全局缓存access_token)

            string access_token = GetAccessToken();

            //2. 用第一步拿到的access_token 采用http GET方式请求获得jsapi_ticket(有效期7200秒,开发者必须在自己的服务全局缓存jsapi_ticket)
            string url2 = $"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={access_token}&type=jsapi";
            string result2 = HttpService.Get(url2);
            JsonData jd2 = JsonMapper.ToObject(result2);
            string ticket = (string)jd2["ticket"];

            //3. 开始签名
            string now_url = HttpContext.Current.Request.Url.AbsoluteUri;
            string no_jiami = $"jsapi_ticket={ticket}&noncestr={noncestr}×tamp={timestamp}&url={now_url}";
            //SHA1加密
            signature = FormsAuthentication.HashPasswordForStoringInConfigFile(no_jiami, "SHA1");

            WxPayData data = new WxPayData();
            data.SetValue("appId", appid);
            data.SetValue("timestamp", timestamp);
            data.SetValue("nonceStr", noncestr);
            data.SetValue("signature", signature);

            //   Log.Debug(this.GetType().ToString(), "使用微信JS-SDK接口的配置 : " + data.ToPrintStr());

            return data;
        }

        ////// 发送模板消息
        //////发送给用户的OPENID///模板ID///JSON字符串///返回远程的JSON字符串public string SendTemplateMsg(string touser,  string jsonstr)
        {
  

            //1. 获取AccessToken(有效期7200秒,开发者必须在自己的服务全局缓存access_token)

            string access_token = GetAccessToken();

            string url2 = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}";
            StringBuilder sb = new StringBuilder();
            //sb.Append("{\"touser\":\"o7-JIxIGFZ31PvoX366C9o8WS5Z8\",\"template_id\":\"LiK9vj36_OdVcgN5YSGkSlWdanlmd-tNpFbtZ0G7sSc\",\"url\":\"http://weixin.qq.com/download\",\"topcolor\":\"#FF0000\",\"data\":{\"name\":{\"value\":\"牛腩测试商品\"},\"remark\":{\"value\":\"提取码:4547892564389\"}}}");
            sb.Append(jsonstr);

            Log.Info("wx", "发送:"+sb.ToString());

            string result2 = HttpService.PostJSON(sb.ToString(), url2);
            return result2;
        }

        public string SendTemplateMsg_yymsg(string touser, string firststr, int yycount,string url) {
            Hashtable ht = new Hashtable();
            ht.Add("touser", touser);
            ht.Add("template_id", "nKfIqNprxEgyaiYTlEdAJPMGd6wabvI5XiGYCBM3aPs");
            ht.Add("url", url);
            var f = new { value = firststr };
            var k1 = new { value = "集萃堂" };
            var k2 = new { value = yycount + " 人" };
            var k3 = new { value = DateTime.Now.ToString("yyyy年MM月dd日")+GetXingQi_ALL(DateTime.Now) };
            var r = new { value = "预约人数只计算已缴费未就诊的用户" };
            var m = new {
                first = f,
                keyword1 = k1,
                keyword2 = k2,
                keyword3 = k3,
                remark = r,
            };
            ht.Add("data",m);
            string jsonstr = LitJson.JsonMapper.ToJson(ht);
            return SendTemplateMsg(touser, jsonstr);
        }

        ////// 上传临时素材
        /// 返回media_id
        /////////public string UploadLinShiSuCai(int userid)
        {
            string imgpath = HttpContext.Current.Server.MapPath($"/upload/erweima/{userid}_2.png");
            string appid = WxPayConfig.APPID;
            string secret = WxPayConfig.APPSECRET;

            //1. 获取AccessToken(有效期7200秒,开发者必须在自己的服务全局缓存access_token)

            string access_token = GetAccessToken();

            string url2 = $"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=image";

            //图片转为流
            Image img = new Bitmap(imgpath);
            MemoryStream stream = new MemoryStream();
            img.Save(stream, ImageFormat.Png);
            BinaryReader br = new BinaryReader(stream);
            byte[] data = stream.ToArray();
            stream.Close();



            var boundary = "fbce142e-4e8e-4bf3-826d-cc3cf506cccc";
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("User-Agent", "KnowledgeCenter");
            client.DefaultRequestHeaders.Remove("Expect");
            client.DefaultRequestHeaders.Remove("Connection");
            client.DefaultRequestHeaders.ExpectContinue = false;
            client.DefaultRequestHeaders.ConnectionClose = true;
            var content = new MultipartFormDataContent(boundary);
            content.Headers.Remove("Content-Type");
            content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
            var contentByte = new ByteArrayContent(data);
            content.Add(contentByte);
            contentByte.Headers.Remove("Content-Disposition");
            contentByte.Headers.TryAddWithoutValidation("Content-Disposition", $"form-data; name=\"media\";filename=\"{userid}_2.png\"" + "");
            contentByte.Headers.Remove("Content-Type");
            contentByte.Headers.TryAddWithoutValidation("Content-Type", "image/png");
            try
            {
                var result2 = client.PostAsync(url2, content);
                if (result2.Result.StatusCode != HttpStatusCode.OK)
                    throw new Exception(result2.Result.Content.ReadAsStringAsync().Result);
                string jsonstr = result2.Result.Content.ReadAsStringAsync().Result;
                JsonData jd2 = JsonMapper.ToObject(jsonstr);
                string result = (string)jd2["media_id"];
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + ex.InnerException.Message);
            }

        }

        ////// 取微信公众号二维码,带int参数
        /////////返回二维码的链接public string GetErWeiMa(int userid)
        {

            //1. 获取AccessToken(有效期7200秒,开发者必须在自己的服务全局缓存access_token)

            string access_token = GetAccessToken();

            string url2 = $"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={access_token}";
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + userid + "}}}");
            string result2 = HttpService.PostJSON(sb.ToString(), url2);

            JsonData jd2 = JsonMapper.ToObject(result2);
            string ticket = (string)jd2["ticket"];

            //二维码图片地址
            string url3 = $"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={ticket}";


            return url3;

        }

        ////// 客服发送消息
        /// https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140547
        //////public string SendMessage(string jsonstr)
        {

            //1. 获取AccessToken(有效期7200秒,开发者必须在自己的服务全局缓存access_token) 
            string access_token = GetAccessToken();

            string url2 = $"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={access_token}";
            string result2 = HttpService.PostJSON(jsonstr, url2);
            return result2;
        }
        ////// 发送文本消息
        ////////////public string SendMessage_Text(string openid, string msg)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("    \"touser\":\"" + openid + "\",");
            sb.Append("    \"msgtype\":\"text\",");
            sb.Append("    \"text\":");
            sb.Append("    {");
            sb.Append("         \"content\":\"" + msg + "\"");
            sb.Append("    }");
            sb.Append("}");
            string res = new WxPayAPI.NiunanWXHelper().SendMessage(sb.ToString());
            return res;
        }
        ////// 发送图片消息
        ////////////public string SendMessage_Image(string openid, string media_id)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("    \"touser\":\"" + openid + "\",");
            sb.Append("    \"msgtype\":\"image\",");
            sb.Append("    \"image\":");
            sb.Append("    {");
            sb.Append("         \"media_id\":\"" + media_id + "\"");
            sb.Append("    }");
            sb.Append("}");
            string res = new WxPayAPI.NiunanWXHelper().SendMessage(sb.ToString());
            return res;
        }

        ////// 取永久素材列表
        //////public string GetSuCaiList()
        {
            string appid = WxPayConfig.APPID;
            string secret = WxPayConfig.APPSECRET;

            //1. 获取AccessToken(有效期7200秒,开发者必须在自己的服务全局缓存access_token)
            string url1 = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
            string result = HttpService.Get(url1);
            JsonData jd = JsonMapper.ToObject(result);
            string access_token = (string)jd["access_token"];

            string url2 = $"https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={access_token}";
            string jsonstr = "{" +
                                   "\"type\":\"image\"," +
                                   "\"offset\":0," +
                                   "\"count\":5" +
                               " }";
            string result2 = HttpService.PostJSON(jsonstr, url2);
            return result2;

        }

        ////// 传入微信OPENID,取用户信息
        /// 用户没有订阅公众号则取不到
        ////////////////////////public void GetUserInfo(string wxopenid, out string nickname, out int sex, out string headimgurl, out string country, out string province, out string city)
        {
            string appid = WxPayConfig.APPID;
            string secret = WxPayConfig.APPSECRET;
            nickname = "";
            sex = 0;
            headimgurl = "";
            country = "";
            province = "";
            city = "";

            //1. 获取AccessToken(有效期7200秒,开发者必须在自己的服务全局缓存access_token)

            string access_token = GetAccessToken();

            string url2 = $"https://api.weixin.qq.com/cgi-bin/user/info?access_token={access_token}&openid={wxopenid}&lang=zh_CN ";
            string result = HttpService.Get(url2);
            Log.Info(this.GetType().ToString(), "\r\n取微信用户信息返回: " + result);
            JsonData jd = JsonMapper.ToObject(result);
            int subscribe = (int)jd["subscribe"];
            if (subscribe == 1)
            {
                nickname = (string)jd["nickname"];
                sex = (int)jd["sex"];
                headimgurl = (string)jd["headimgurl"];
                country = (string)jd["country"];
                province = (string)jd["province"];
                city = (string)jd["city"];
            }

        }

        ////// 取微信openid,传入当前的页面URL用于返回
        //////public string GetOpenid(string redirect_uri)
        {
            string str = "";
            if (HttpContext.Current.Session["openid"] != null && !string.IsNullOrEmpty(HttpContext.Current.Session["openid"].ToString()))
            {
                str = HttpContext.Current.Session["openid"].ToString();

            }
            else
            {
                string code = HttpContext.Current.Request.QueryString["code"];
                if (string.IsNullOrEmpty(code))
                {
                    #region 构造网页授权获取code的URL 

                    WxPayData data = new WxPayData();
                    data.SetValue("appid", WxPayConfig.APPID);
                    data.SetValue("redirect_uri", redirect_uri);
                    data.SetValue("response_type", "code");
                    data.SetValue("scope", "snsapi_userinfo");
                    data.SetValue("state", "STATE" + "#wechat_redirect");
                    string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();

                    try
                    {
                        //触发微信返回code码         
                        HttpContext.Current.Response.Redirect(url);//Redirect函数会抛出ThreadAbortException异常,不用处理这个异常
                    }
                    catch (System.Threading.ThreadAbortException ex)
                    {
                    }
                    #endregion
                }
                else
                {
                    #region 根据OPENID查最近一次预约,有则显示,无则取最后一次预约对应的挂号单,没结账就显示前面还有几位
                    //构造获取openid及access_token的url
                    WxPayData data = new WxPayData();
                    data.SetValue("appid", WxPayConfig.APPID);
                    data.SetValue("secret", WxPayConfig.APPSECRET);
                    data.SetValue("code", code);
                    data.SetValue("grant_type", "authorization_code");
                    string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl();

                    //请求url以获取数据
                    string result = HttpService.Get(url);
                    //保存access_token,用于收货地址获取
                    JsonData jd = JsonMapper.ToObject(result);
                    string access_token = (string)jd["access_token"];

                    //获取用户openid
                    str = (string)jd["openid"];


                    #endregion
                }
            }
            return str;
        }

        ////// 公众号可以使用本接口获取从JSSDK的uploadVoice接口上传的临时语音素材,格式为speex,16K采样率。该音频比上文的临时素材获取接口(格式为amr,8K采样率)更加清晰,适合用作语音识别等对音质要求较高的业务。
        /////////public string DownloadMediaJSSDK(string media_id,int chatid) {
            string access_token = GetAccessToken();
            string url = $"https://api.weixin.qq.com/cgi-bin/media/get/jssdk?access_token={access_token}&media_id={media_id}";
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            request = (HttpWebRequest)WebRequest.Create(url); 
            request.Method = "GET";
            //获取服务器返回
            response = (HttpWebResponse)request.GetResponse();
            byte[] buffer = new byte[1024]; 
            Stream inStream = response.GetResponseStream();
            string FileName = HttpContext.Current.Server.MapPath($"/upload/chat/{chatid}.speex");
            Stream outStream = System.IO.File.Create(FileName);
            int l;
            do
            {
                l = inStream.Read(buffer, 0, buffer.Length);
                if (l > 0)
                    outStream.Write(buffer, 0, l);
            }
            while (l > 0);

            outStream.Close();
            inStream.Close();
             
            string result = "下载的东西保存路径 :"+ FileName;
            return result;
        }
    }
}