码迷,mamicode.com
首页 > 微信 > 详细

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

时间:2016-09-09 11:51:56      阅读:914      评论:0      收藏:0      [点我收藏+]

标签:

当前微信接口类已实现以下接口,代码上如果不够简洁的,请自行处理。
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_token无效。请开发者认真比对AppSecret的正确性,或查看是否正在为恰当的公众号调用接口
                        WeChatSMS.SetAccess_Token();
                        GetUserInfo(OPENID);
                    }
                    else
                    {
                        LogControls.InsertLogs(json, "分享获取用户信息异常");
                        json = "";
                        break;
                    }
                    LogControls.InsertLogs(json, "分享获取用户信息异常--循环");
                }
            }

            return json;
        }
        #endregion

        #region 网页授权获取用户基本信息
        public static string WebAccreditUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect";
        /// <summary>
        /// 网页授权获取用户基本信息链接(redirect_uri/?code=CODE&state=STATE)
        /// </summary>
        /// <param name="url">授权后重定向的回调链接地址,请使用urlencode对链接进行处理</param>
        /// <param name="scope">应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)</param>
        /// <param name="state">重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节</param>
        /// <returns></returns>
        public static string GetWebAccreditUrl(string redirect_uri, string scope, string state)
        {
            return string.Format(WebAccreditUrl, APPID, redirect_uri, scope, state);
        }
        /// <summary>
        /// 通过code换取网页授权access_token
        /// </summary>
        public static string WebAccess_tokenUrl = " https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";

        /// <summary>
        /// 通过code换取网页授权access_token
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string GetWebAccess_token(string code)
        {
            string url = string.Format(WebAccess_tokenUrl, APPID, SECRET, code);
            return GetJsonByCode(url, "GET", "", "通过code换取网页授权access_token异常");
        }

        /// <summary>
        /// 刷新access_token
        /// </summary>
        public static string WebRefreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}";
        /// <summary>
        /// 刷新access_token,refresh_token有效期为30天,当refresh_token失效之后,需要用户重新授权。
        /// </summary>
        public static string RefreshToken(string refresh_token)
        {
            string url = string.Format(WebRefreshTokenUrl, APPID, refresh_token);
            return GetJsonByCode(url, "GET", "", "刷新access_token异常");
        }
        /// <summary>
        /// 拉取用户信息(需scope为 snsapi_userinfo)
        /// </summary>
        public static string WebUserinfo = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
        /// <summary>
        /// 拉取用户信息(需scope为 snsapi_userinfo)
        /// </summary>
        /// <param name="access_token"></param>
        /// <returns></returns>
        public static string GetWebUserInfo(string access_token)
        {
            string url = string.Format(WebUserinfo, access_token, APPID);
            return GetJsonByCode(url, "GET", "", "拉取用户信息(需scope为 snsapi_userinfo)异常");
        }
        /// <summary>
        /// 检验授权凭证(access_token)是否有效
        /// </summary>
        public static string WebAccess_TokenIsValidUrl = "https://api.weixin.qq.com/sns/auth?access_token={0}&openid={1}";
        /// <summary>
        /// 检验授权凭证(access_token)是否有效
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="openID"></param>
        /// <returns></returns>
        public static string ValidAccess_Token(string access_token, string openID)
        {
            string url = string.Format(WebAccess_TokenIsValidUrl, access_token, openID);
            return GetJsonByCode(url, "GET", "", "检验授权凭证(access_token)是否有效异常");
        }

        #endregion

        /// <summary>
        /// 通用接口请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Method">POST或者GET</param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpPost(string Url, string Method, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = Method;
            request.ContentType = "application/x-www-form-urlencoded";
            if (string.IsNullOrWhiteSpace(postDataStr) == false)
            {
                byte[] dataArray = Encoding.UTF8.GetBytes(postDataStr);
                request.ContentLength = dataArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(dataArray, 0, dataArray.Length);
                dataStream.Close();
            }
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                String res = reader.ReadToEnd();
                reader.Close();
                return res;
            }
            catch (Exception e)
            {
                return e.Message + e.ToString();
            }
        }

        /// <summary>
        /// 获取微信返回json语句
        /// </summary>
        /// <param name="objUrl"></param>
        /// <param name="Method"></param>
        /// <param name="postDataStr"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        public static string GetJson(string objUrl, string Method, string postDataStr, string category)
        {
            string resultJson = "";
            while (true)
            {
                string url = string.Format(objUrl, GetAccess_Token());
                string json = HttpPost(url, Method, postDataStr);
                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 if (errcode == "0")
                    {
                        resultJson = json;
                        break;
                    }
                    else
                    {
                        LogControls.InsertLogs(json, category);
                        break;
                    }
                }
                else
                {
                    resultJson = json;
                    break;
                }
            }
            return resultJson;
        }


        /// <summary>
        /// 获取微信返回json语句
        /// </summary>
        /// <param name="url"></param>
        /// <param name="Method"></param>
        /// <param name="postDataStr"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        public static string GetJsonByCode(string url, string Method, string postDataStr, string category)
        {
            string resultJson = "";
            while (true)
            {
                string json = HttpPost(url, Method, postDataStr);
                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 == "0")
                    {
                        resultJson = json;
                        break;
                    }
                    else if (errcode == "40029")
                    {
                        //40029不合法的oauth_code  Code无效错误
                        resultJson = json;
                        break;
                    }
                    else if (errcode == "40003")
                    {
                        //40003不合法的OpenID,请开发者确认OpenID(该用户)是否已关注公众号,或是否是其他公众号的OpenID
                        resultJson = json;
                        break;
                    }
                    else
                    {
                        LogControls.InsertLogs(json, category);
                        break;
                    }
                }
                else
                {
                    resultJson = json;
                    break;
                }
            }
            return resultJson;
        }
    }


    /// <summary>
    /// 微信文件上传通用类
    /// </summary>
    public static class UploadVideo
    {
        /// <summary>  
        /// 填充表单信息的Stream  
        /// </summary>  
        /// <param name="formData"></param>  
        /// <param name="stream"></param>  
        public static void FillFormDataStream(this Dictionary<string, string> formData, Stream stream)
        {
            string dataString = GetQueryString(formData);
            var formDataBytes = formData == null ? new byte[0] : Encoding.UTF8.GetBytes(dataString);
            stream.Write(formDataBytes, 0, formDataBytes.Length);
            stream.Seek(0, SeekOrigin.Begin);//设置指针读取位置  
        }

        public static string GetUploadVideoResult(string urlTemplate, string accessToken, string type, string filePath, string title, string introduction)  
        {
           //"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}"
            var url = string.Format(urlTemplate, accessToken, type);  
            var fileDictionary = new Dictionary<string, string>();  
            fileDictionary["media"] = filePath;
            if (title != "")
            {
                fileDictionary["description"] = string.Format("{{\"title\":\"{0}\", \"introduction\":\"{1}\"}}", title, introduction);
            }
  
            string returnText = string.Empty;  
            Dictionary<string, string> postDataDictionary = null;  
            using (MemoryStream ms = new MemoryStream())  
            {  
                postDataDictionary.FillFormDataStream(ms); //填充formData  
                returnText = HttpPost(url, null, ms, fileDictionary, null, null, 1200000);  
            }  
            return returnText;  
        }  
  
  
        /// <summary>  
        /// 组装QueryString的方法  
        /// 参数之间用&连接,首位没有符号,如:a=1&b=2&c=3  
        /// </summary>  
        /// <param name="formData"></param>  
        /// <returns></returns>  
        public static string GetQueryString(this Dictionary<string, string> formData)  
        {  
            if (formData == null || formData.Count == 0)  
            {  
                return "";  
            }  
  
            StringBuilder sb = new StringBuilder();  
  
            var i = 0;  
            foreach (var kv in formData)  
            {  
                i++;  
                sb.AppendFormat("{0}={1}", kv.Key, kv.Value);  
                if (i < formData.Count)  
                {  
                    sb.Append("&");  
                }  
            }  
  
            return sb.ToString();  
        }  
  
        /// <summary>  
        /// 根据完整文件路径获取FileStream  
        /// </summary>  
        /// <param name="fileName"></param>  
        /// <returns></returns>  
        public static FileStream GetFileStream(string fileName)  
        {  
            FileStream fileStream = null;  
            if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))  
            {  
                fileStream = new FileStream(fileName, FileMode.Open);  
            }  
            return fileStream;  
        }  
  
        /// <summary>  
        /// 使用Post方法获取字符串结果  
        /// </summary>  
        /// <param name="url"></param>  
        /// <param name="cookieContainer"></param>  
        /// <param name="postStream"></param>  
        /// <param name="fileDictionary">需要上传的文件,Key:对应要上传的Name,Value:本地文件名</param>  
        /// <param name="timeOut">超时</param>  
        /// <returns></returns>  
        public static string HttpPost(string url, CookieContainer cookieContainer = null, Stream postStream = null, Dictionary<string, string> fileDictionary = null, string refererUrl = null, Encoding encoding = null, int timeOut = 1200000)  
        {  
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);  
            request.Method = "POST";  
            request.Timeout = timeOut;  
 
            #region 处理Form表单文件上传  
            var formUploadFile = fileDictionary != null && fileDictionary.Count > 0;//是否用Form上传文件  
            if (formUploadFile)  
            {  
                //通过表单上传文件  
                postStream = postStream ?? new MemoryStream();  
  
                string boundary = "----" + DateTime.Now.Ticks.ToString("x");  
                //byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");  
                string fileFormdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";  
                string dataFormdataTemplate = "\r\n--" + boundary +  
                                              "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";  
                foreach (var file in fileDictionary)  
                {  
                    try  
                    {  
                        var fileName = file.Value;  
  
                        //准备文件流  
                        using (var fileStream = GetFileStream(fileName))  
                        {  
                            string formdata = null;  
                            if (fileStream != null)  
                            {  
                                //存在文件  
                                formdata = string.Format(fileFormdataTemplate, file.Key, /*fileName*/ Path.GetFileName(fileName));  
                            }  
                            else  
                            {  
                                //不存在文件或只是注释  
                                formdata = string.Format(dataFormdataTemplate, file.Key, file.Value);  
                            }  
  
                            //统一处理  
                            var formdataBytes = Encoding.UTF8.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要换行  
                            postStream.Write(formdataBytes, 0, formdataBytes.Length);  
  
                            //写入文件  
                            if (fileStream != null)  
                            {  
                                byte[] buffer = new byte[1024];  
                                int bytesRead = 0;  
                                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)  
                                {  
                                    postStream.Write(buffer, 0, bytesRead);  
                                }  
                            }  
                        }  
                    }  
                    catch (Exception ex)  
                    {  
                        throw ex;  
                    }  
                }  
                //结尾  
                var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");  
                postStream.Write(footer, 0, footer.Length);  
  
                request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);  
            }  
            else  
            {  
                request.ContentType = "application/x-www-form-urlencoded";  
            }  
            #endregion  
  
            request.ContentLength = postStream != null ? postStream.Length : 0;  
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";  
            request.KeepAlive = true;  
  
            if (!string.IsNullOrEmpty(refererUrl))  
            {  
                request.Referer = refererUrl;  
            }  
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";  
  
            if (cookieContainer != null)  
            {  
                request.CookieContainer = cookieContainer;  
            }  
 
            #region 输入二进制流  
            if (postStream != null)  
            {  
                postStream.Position = 0;  
  
                //直接写入流  
                Stream requestStream = request.GetRequestStream();  
  
                byte[] buffer = new byte[1024];  
                int bytesRead = 0;  
                while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)  
                {  
                    requestStream.Write(buffer, 0, bytesRead);  
                }  
  
                //debug  
                postStream.Seek(0, SeekOrigin.Begin);  
                StreamReader sr = new StreamReader(postStream);  
                var postStr = sr.ReadToEnd();  
                postStream.Close();//关闭文件访问  

            }  
            #endregion  
  
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
  
            if (cookieContainer != null)  
            {  
                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);  
            }  
  
            using (Stream responseStream = response.GetResponseStream())  
            {  
                using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))  
                {  
                    string retString = myStreamReader.ReadToEnd();  
                    return retString;  
                }  
            }  
        } 
    }
}

 

分享朋友圈用到了一般应用程序
 public class wxconfig
    {
        public string appId { get; set; }
        public string timestamp { get; set; }
        public string nonceStr { get; set; }
        public string jsapiticke { get; set; }
        public string url { get; set; }
        public string signature
        {
            get
            {
                string temp = Cryptography.SHA1_Hash("jsapi_ticket=" + jsapiticke + "&noncestr="
                    + nonceStr + "&timestamp=" + timestamp + "&url=" + url).ToLower();
                return temp;

        } }
    }

    /// <summary>
    /// Getjsapi 的摘要说明
    /// </summary>
    public class Getjsapi : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            wxconfig item = new wxconfig();
            item.jsapiticke = WeChatSMS.GetJsapi_Ticket();
            item.url = context.Request.Params["urlparam"];
            item.appId = WeChatSMS.APPID;
            item.timestamp = WeChatSMS.GetTimeStamp();
            item.nonceStr = ("GGVi4C3VM0P37wVU");
            JavaScriptSerializer js = new JavaScriptSerializer();
            string json = js.Serialize(item);
            context.Response.Write(json);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

页面配置代码

  <script>
        $.ajax({
            type: "POST",
            url: "/ashx/Getjsapi.ashx",
            data: { urlparam: "http://www.chaoyundong.com/mobile/share/sharetest.aspx" },
            cache: false,
            async: false, //是否ajax同步
            success: function (data) {
               var item = JSON.parse(data);
                //console.log(item);
                wx.config({
                    debug: false,
                    appId: item.appId,
                    timestamp: item.timestamp,
                    nonceStr: item.nonceStr,
                    signature: item.signature,
                    jsApiList: [
                        checkJsApi,
                        onMenuShareTimeline,
                        onMenuShareAppMessage
                    ]
                });
                wx.ready(function () {
                    //分享到朋友圈
                    wx.onMenuShareTimeline({
                        title: 测试哈哈哈, // 分享标题
                        link: http://movie.douban.com/subject/25785114/, // 分享链接
                        imgUrl: http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg, // 分享图标
                        success: function (res) {
                            //console.log(res);
                            alert(112234);
                        },
                        cancel: function () {
                            alert(3333333);
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    //分享到朋友
                    wx.onMenuShareAppMessage({
                        title: 测试哈哈哈, // 分享标题
                        link: http://movie.douban.com/subject/25785114/, // 分享链接
                        imgUrl: http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg, // 分享图标
                        success: function (res) {
                            //console.log(res);
                            alert(112234);
                        },
                        cancel: function () {
                            alert(3333333);
                            // 用户取消分享后执行的回调函数
                        }
                    });
                });                
            }
        });        
    </script>

 

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

标签:

原文地址:http://www.cnblogs.com/caiyt/p/5855741.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!