• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

asp.netC#实现微信接口权限开发类

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
当前微信接口类已实现以下接口,代码上如果不够简洁的,请自行处理。
1.获取access_token
2.获取用户基本信息
3.生成带参数二维码
4.新增永久素材
5.新增临时素材
6.发送微信模版
7.网页授权获取用户基本信息
8.分享朋友圈
关于需要使用poststr字符串可以在asp.net 页面进行poststr配置

//获取素材列表
var jsonitem = new
{
type = "image",
offset = 0,
count = 999
};
JavaScriptSerializer js = new JavaScriptSerializer();
string poststr = js.Serialize(jsonitem);

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace DomainModel.Model
{
    public class WeChatSMS
    {
     //该类有用到数据库表WeChatAccessTokens保存和Log日志,这两个表可以根据自己喜好自行创建
        /// <summary>
        /// AppID(应用ID)
        /// </summary>
        public static string APPID = "APPID";
        /// <summary>
        /// AppSecret(应用密钥)
        /// </summary>
        private static string SECRET = "SECRET";

        #region 微信模板ID
        /// <summary>
        /// 兑换码领取成功通知
        /// </summary>
        public static string Template = "zjXZufqN-9RguRy5T9QQ9N1ueSEkkcbPiRlzWe0XUmI";
        /// <summary>
        /// 校验码通知
        /// </summary>
        public static string ConcertTemplate = "tIuE4GJIKO3wAoyt-GawmTi03tdOqlg9CHw0IwcZVsk";
        /// <summary>
        /// 领取成功通知
        /// </summary>
        public static string GetTemplate = "mpADikrfOojgF7S-_zhTxgqB7F4hy_6qwAYd8f-g_sU";
        #endregion
        
        /// <summary>  
        /// 获取时间戳  
        /// </summary>  
        /// <returns></returns>  
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        #region access_token
        /// <summary>
        /// 获取access_token
        /// </summary>
        /// <returns></returns>
        public static string GetAccess_Token()
        {
            using (DB db = DBFactory.CreateDB())
            {
                var list = db.WeChatAccessTokens.Where(s => s.APPID == WeChatSMS.APPID && s.ParamName == "access_token").ToList();
                if (list.Count == 1)
                {
                    if (list[0].UpdateDate.AddHours(2) > DateTime.Now)
                    {
                        return list[0].AccessToken;
                    }
                }
            }

            return SetAccess_Token();
        }

        /// <summary>
        /// 获取access_token
        /// </summary>
        private static string TOKENURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";

        /// <summary>
        /// 更新access_token
        /// </summary>
        /// <returns></returns>
        public static string SetAccess_Token()
        {
            string url = string.Format(WeChatSMS.TOKENURL,WeChatSMS.APPID, WeChatSMS.SECRET);
            string json = HttpPost(url, "GET", "");
            string pattern = "^{\"access_token\":\"(?<access_token>.+?)\"";
            Regex regex = new Regex(pattern);
            var match = regex.Match(json);
            string AccessToken = "";
            if (match.Success)
            {
                AccessToken = match.Result("${access_token}");
                using (DB db = DBFactory.CreateDB())
                {
                    var list = db.WeChatAccessTokens.Where(s => s.APPID == WeChatSMS.APPID && s.ParamName == "access_token").ToList();
                    if (list.Count == 1)
                    {
                        list[0].AccessToken = AccessToken;
                        list[0].UpdateDate = DateTime.Now;
                    }
                    else
                    {
                        WeChatAccessToken item = new WeChatAccessToken();
                        item.APPID = WeChatSMS.APPID;
                        item.ParamName = "access_token";
                        item.AccessToken = AccessToken;
                        item.UpdateDate = DateTime.Now;
                        db.WeChatAccessTokens.InsertOnSubmit(item);
                    }
                    db.SubmitChanges();
                }
            }
            return AccessToken;
        }
        #endregion

        #region jsapi_ticket

        /// <summary>
        /// 获取jsapi_ticket
        /// </summary>
        private static string JSAPI_TICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi";
        /// <summary>
        /// 获取jsapi_ticket
        /// </summary>
        /// <returns></returns>
        public static string GetJsapi_Ticket()
        {
            using (DB db = DBFactory.CreateDB())
            {
                var list = db.WeChatAccessTokens.Where(s => s.APPID == WeChatSMS.APPID && s.ParamName == "jsapi_ticket").ToList();
                if (list.Count == 1)
                {
                    if (list[0].UpdateDate.AddHours(2) > DateTime.Now)
                    {
                        return list[0].AccessToken;
                    }
                }
            }

            return SetJsapi_Ticket();
        }

        /// <summary>
        /// 更新jsapi_ticket
        /// </summary>
        /// <returns></returns>
        public static string SetJsapi_Ticket()
        {
            string JsapiTicket = "";

            string json = GetJson(JSAPI_TICKET, "GET", "", "分享微信信息异常记录");

            string pattern = "\"ticket\":\"(?<ticket>.+?)\",";
            Regex regex = new Regex(pattern);
            var match = regex.Match(json);
            if (match.Success)
            {
                JsapiTicket = match.Result("${ticket}");
                using (DB db = DBFactory.CreateDB())
                {
                    var list = db.WeChatAccessTokens.Where(s => s.APPID == WeChatSMS.APPID && s.ParamName == "jsapi_ticket").ToList();
                    if (list.Count == 1)
                    {
                        list[0].AccessToken = JsapiTicket;
                        list[0].UpdateDate = DateTime.Now;
                    }
                    else
                    {
                        WeChatAccessToken item = new WeChatAccessToken();
                        item.APPID = WeChatSMS.APPID;
                        item.ParamName = "jsapi_ticket";
                        item.AccessToken = JsapiTicket;
                        item.UpdateDate = DateTime.Now;
                        db.WeChatAccessTokens.InsertOnSubmit(item);
                    }
                    db.SubmitChanges();
                }
            }
            return JsapiTicket;
        }
        #endregion

        #region 素材管理

        public static string uploadTemporaryUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}";
        /// <summary>
        /// 新增临时素材
        /// </summary>
        /// <param name="type">上传文件类型</param>
        /// <param name="filePath">文件的绝对路径</param>
        /// <returns></returns>
        public static string UploadTemporaryFile(string type, string filePath)
        {
           return UploadData(uploadTemporaryUrl, "POST", type, filePath, "新增临时素材");                    
        }


        public static string uploadPerpetualUrl = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}";
        /// <summary>
        /// 新增永久素材
        /// </summary>
        /// <param name="type">上传文件类型</param>
        /// <param name="filePath">文件的绝对路径</param>
        /// <returns></returns>
        public static string UploadPerpetualFile(string type, string filePath)
        {
            return UploadData(uploadPerpetualUrl, "POST", type, filePath, "新增永久素材");            
        }
        

        /// <summary>
        /// 上传永久通用 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="type"></param>
        /// <param name="filePath"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        public static string UploadData(string url, string method, string type, string localPath, string category)
        {
            string resultJson = "";
            while (true)
            {
                string json = UploadVideo.GetUploadVideoResult(url, GetAccess_Token(), type, localPath, "", "");
                string pattern = "^{\"errcode\":(?<errcode>.+?),";
                Regex regex = new Regex(pattern);
                var match = regex.Match(json);
                if (match.Success)
                {
                    string errcode = match.Result("${errcode}");
                    if (errcode == "-1")
                    {
                        //-1系统繁忙,此时请开发者稍候再试\
                        break;
                    }
                    else if (errcode == "42001")
                    {
                        //42001access_token超时,请检查access_token的有效期,请参考基础支持-获取access_token中,对access_token的详细机制说明 
                        SetAccess_Token();
                    }
                    else if (errcode == "40001")
                    {
                        //40001获取access_token时AppSecret错误,或者access_token无效。请开发者认真比对AppSecret的正确性,或查看是否正在为恰当的公众号调用接口
                        SetAccess_Token();
                    }
                    else
                    {
                        LogControls.InsertLogs(json, category);
                        break;
                    }
                }
                else
                {
                    pattern = "\"media_id\":\"(?<media_id>.+?)\",";
                    regex = new Regex(pattern);
                    match = regex.Match(json);
                    if (match.Success)
                    {
                        resultJson = json;
                        break;
                    }
                }
            }

            return resultJson;
        }

        public static string uploadImageUrl = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={0}";
        /// <summary>
        /// 新增图文中的图片素材
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filePath"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        public static string UploadImage(string filePath)
        {
            string resultJson = "";
            using (WebClient client = new WebClient())
            {
                while (true)
                {
                    byte[] b = client.UploadFile(string.Format(uploadImageUrl, GetAccess_Token()), filePath);//调用接口上传文件
                    string json = Encoding.Default.GetString(b);//获取返回值
                    string pattern = "^{\"errcode\":(?<errcode>.+?),";
                    Regex regex = new Regex(pattern);
                    var match = regex.Match(json);
                    if (match.Success)
                    {
                        string errcode = match.Result("${errcode}");
                        if (errcode == "-1")
                        {
                            //-1系统繁忙,此时请开发者稍候再试\
                            break;
                        }
                        else if (errcode == "42001")
                        {
                            //42001access_token超时,请检查access_token的有效期,请参考基础支持-获取access_token中,对access_token的详细机制说明 
                            SetAccess_Token();
                        }
                        else if (errcode == "40001")
                        {
                            //40001获取access_token时AppSecret错误,或者access_token无效。请开发者认真比对AppSecret的正确性,或查看是否正在为恰当的公众号调用接口
                            SetAccess_Token();
                        }
                        else
                        {
                            LogControls.InsertLogs(json, "新增图文中的图片素材");
                            break;
                        }
                    }
                    else
                    {
                        if (json.Contains("url"))
                        {
                            resultJson = json.Replace("\\","");
                            break;
                        }
                    }
                }
            }
            return resultJson;  
        }

        /// <summary>
        /// 获取素材列表
        /// </summary>
        public static string BatchgetMaterialUrl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={0}";
        /// <summary>
        /// 获取素材列表
        /// </summary>
        /// <returns></returns>
        public static string GetBatchget_Material(string postDataStr)
        {
            return GetJson(BatchgetMaterialUrl, "POST", postDataStr, "获取素材列表信息异常");            
        }
        #endregion

        #region 带参数二维码
        public const string CreateTicketUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={0}";
        /// <summary>
        /// 创建二维码ticket
        /// </summary>
        public static string GetCreateTicket(string postDataStr)
        {
            return GetJson(CreateTicketUrl, "POST", postDataStr, "创建二维码ticket异常");
        }

        public const string GetTicketUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={0}";
        /// <summary>
        /// 通过ticket换取二维码图片路径
        /// </summary>
        /// <param name="ticket"></param>
        /// <returns></returns>
        public static string GetTicketImage(string ticket,string path,string filename)
        {
            try
            {
                string uriStr = string.Format(GetTicketUrl, ticket.Replace("\\", ""));
                HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create(uriStr);
                requestScore.Method = "GET";
                requestScore.ContentType = "image/jpg;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)requestScore.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                Image img = Image.FromStream(myResponseStream);
                string imagePath = HttpContext.Current.Server.MapPath(path + filename);
                string dpath = HttpContext.Current.Server.MapPath(path);
                if (!Directory.Exists(dpath))
                {
                    Directory.CreateDirectory(dpath);
                }
                img.Save(imagePath);
                myResponseStream.Close();
                return path + filename;
            }
            catch (Exception ex)
            {
                LogControls.InsertLogs(ex.ToString() + "\r\n" + ticket, "微信二维码图片异常");
                return "";
            }
        }

        #endregion

        #region 发送模板通用

        /// <summary>
        /// 接口调用请求说明
        /// </summary>
        private static string TEMPLATESEND = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

        /// <summary>
        /// 微信发送模板信息
        /// </summary>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static void SendTemplate(string postDataStr)
        {
            string Url = TEMPLATESEND + GetAccess_Token();
            SendIteration(Url, "POST", postDataStr);          
        }
        /// <summary>
        /// 迭代发送
        /// 42001:access_token超时,请检查access_token的有效期,请参考基础支持-获取access_token中,对access_token的详细机制说明
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Method"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        private static void SendIteration(string Url, string Method, string postDataStr)
        {
            var json = HttpPost(Url, Method, postDataStr);
            string pattern = "^{\"errcode\":(?<errcode>.+?),\"";
            Regex regex = new Regex(pattern);
            var match = regex.Match(json);
            string errcode = "";
            if (match.Success)
            {
                errcode = match.Result("${errcode}");
                if (errcode == "42001")
                {
                    //42001access_token超时,请检查access_token的有效期,请参考基础支持-获取access_token中,对access_token的详细机制说明
                    Url = TEMPLATESEND + SetAccess_Token();
                    SendIteration(Url, Method, postDataStr);
                }                
                else if (errcode == "40001")
                {
                    //40001获取access_token时AppSecret错误,或者access_token无效。请开发者认真比对AppSecret的正确性,或查看是否正在为恰当的公众号调用接口
                    Url = TEMPLATESEND + SetAccess_Token();
                    SendIteration(Url, Method, postDataStr);
                }
                else if (errcode == "43004")
                {
                    //43004需要接收者关注
                }
                else if (errcode != "0")
                {
                    LogControls.InsertLogs(json, "体彩微信信息异常记录");
                }
            }
        }
        #endregion

        #region 获取用户基本信息

        /// <summary>
        /// 获取用户基本资料
        /// </summary>
        public static string UserinfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=";

        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        /// <param name="postDataStr"></param>
        public static string GetUserInfo(string OPENID)
        {
            string Url = UserinfoUrl + GetAccess_Token() + "&openid=" + OPENID + "&lang=zh_CN";
            string json = HttpPost(Url, "GET", "");
            
            Regex rg = new Regex( "^{\"errcode\":(?<errcode>.+?),\"");

            Match match = rg.Match(json);

            if (match.Success)
            {
                while (true)
                {
                    string errcode = match.Result("${errcode}");
                    if (errcode == "42001")
                    {
                        //42001access_token超时,请检查access_token的有效期,请参考基础支持-获取access_token中,对access_token的详细机制说明 
                        WeChatSMS.SetAccess_Token();
                        GetUserInfo(OPENID);
                    }
                    else if (errcode == "40001")
                    {
                        //40001获取access_token时AppSecret错误,或者access_to 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#迭代器、装箱/拆箱、重载等发布时间:2022-07-14
下一篇:
C#获取FTP文件详细备注信息发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap