欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信分享

程序员文章站 2022-03-21 11:51:55
...
    /// <summary>
    /// 获取微信分享接口信息
    /// </summary>
    private void GetWxApiInfo()
    {
       string appId = ""; //微信分享APPID 
       string secret = ""; //公众号的应用秘钥
       string timestamp = string.Empty; //生成签名的时间戳
       string nonceStr = string.Empty; //必填,生成签名的随机串
       string signature = string.Empty;//必填,签名
       string strImg = string.Empty; //分享图片logo
       string strDesc = string.Empty; //微信分享描述信息
       string pageurl = string.Empty; //分享链接
        

        //生成签名的时间戳  
        TimeSpan ts = DateTime.Now - DateTime.Parse("1970-01-01 00:00:00");
        timestamp = ts.TotalSeconds.ToString().Split('.')[0];

        //生成签名的随机串  
        nonceStr = GetRandomString(16, true, true, true, false, "win");

        string token = string.Empty;

        //if (string.IsNullOrWhiteSpace(token))
        //{
        //    //微信access_token,用于获取微信jsapi_ticket      
        //    token = GetAccess_token(appId, secret);

        //    ICore.ICaching.SetCaching("token", token, 60);
        //}

        //微信jsapi_ticket    
        string ticket = ICore.ICaching.GetCaching("ticket");
        //ticket = null;
        if(string.IsNullOrWhiteSpace(ticket))
        {
            //微信access_token,用于获取微信jsapi_ticket      
            token = GetAccess_token(appId, secret);

            //微信jsapi_ticket    
            ticket = GetTicket(token);

            ICore.ICaching.SetCaching("ticket", ticket, 60);
        }
       

        //对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串  
        string str = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + pageurl;

        //签名,使用SHA1生成  
        signature = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1").ToLower();  

    }

    ///<summary>
    ///生成随机字符串 
    ///</summary>
    ///<param name="length">目标字符串的长度</param>
    ///<param name="useNum">是否包含数字,1=包含,默认为包含</param>
    ///<param name="useLow">是否包含小写字母,1=包含,默认为包含</param>
    ///<param name="useUpp">是否包含大写字母,1=包含,默认为包含</param>
    ///<param name="useSpe">是否包含特殊字符,1=包含,默认为不包含</param>
    ///<param name="custom">要包含的自定义字符,直接输入要包含的字符列表</param>
    ///<returns>指定长度的随机字符串</returns>
    public string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
    {
        byte[] b = new byte[4];
        new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
        Random r = new Random(BitConverter.ToInt32(b, 0));
        string s = null, str = custom;
        if (useNum == true) { str += "0123456789"; }
        if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
        if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
        if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
        for (int i = 0; i < length; i++)
        {
            s += str.Substring(r.Next(0, str.Length - 1), 1);
        }
        return s;
    } 


    /// <summary>  
    /// 获取微信jsapi_ticket  
    /// </summary>  
    /// <param name="token">access_token</param>  
    /// <returns>jsapi_ticket</returns>  
    public string GetTicket(string token)
    {
        string ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
        string jsonresult = HttpGet(ticketUrl, "UTF-8");
        WX_Ticket wxTicket = JsonDeserialize<WX_Ticket>(jsonresult);
        return wxTicket.ticket;
    }

    /// <summary>  
    /// 获取微信access_token  
    /// </summary>  
    /// <param name="appid">公众号的应用ID</param>  
    /// <param name="secret">公众号的应用密钥</param>  
    /// <returns>access_token</returns>  
    private string GetAccess_token(string appid, string secret)
    {
        string tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        string jsonresult = HttpGet(tokenUrl, "UTF-8");
        WX_Token wx = JsonDeserialize<WX_Token>(jsonresult);
        return wx.access_token;
    }

    /// <summary>  
    /// JSON反序列化  
    /// </summary>  
    /// <typeparam name="T">实体类</typeparam>  
    /// <param name="jsonString">JSON</param>  
    /// <returns>实体类</returns>  
    private T JsonDeserialize<T>(string jsonString)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        return obj;
    }

    /// <summary>  
    /// HttpGET请求  
    /// </summary>  
    /// <param name="url">请求地址</param>  
    /// <param name="encode">编码方式:GB2312/UTF-8</param>  
    /// <returns>字符串</returns>  
    private string HttpGet(string url, string encode)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "text/html;charset=" + encode;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(encode));
        string retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();

        return retString;
    }
        /// <summary>  
    /// 通过微信API获取access_token得到的JSON反序列化后的实体  
    /// </summary>  
    public class WX_Token
    {
        public string access_token { get; set; }
        public string expires_in { get; set; }
    }

    /// <summary>  
    /// 通过微信API获取jsapi_ticket得到的JSON反序列化后的实体  
    /// </summary>  
    public class WX_Ticket
    {
        public string errcode { get; set; }
        public string errmsg { get; set; }
        public string ticket { get; set; }
        public string expires_in { get; set; }
    } 
 



前端页面:
需要引用js
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>

    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId: '<%=appId%>', // 必填,公众号的唯一标识
        timestamp: '<%=timestamp%>', // 必填,生成签名的时间戳
        nonceStr: '<%=nonceStr%>', // 必填,生成签名的随机串 
        signature: '<%=signature%>', // 必填,签名
        jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo']// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
    })

    wx.ready(function () {
        //分享到朋友圈
        wx.onMenuShareTimeline({
            title: '<%=title%>', // 分享标题
            link: '<%=pageurl%>', // 分享链接
            imgUrl: '<%=strImg%>', // 分享图标
            success: function () {
                
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
               
                // 用户取消分享后执行的回调函数
            }
        });
        //分享给朋友
        wx.onMenuShareAppMessage({
            title: '<%=title%>', // 分享标题
            desc: '<%=strDesc%>', // 分享描述
            link: '<%=pageurl%>', // 分享链接
            imgUrl: '<%=strImg%>', // 分享图标
            type: '', // 分享类型,music、video或link,不填默认为link
            dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
            success: function () {
                
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                
                // 用户取消分享后执行的回调函数
            }
        });
        //分享给QQ好友
        wx.onMenuShareQQ({
            title: '<%=title%>', // 分享标题
            desc: '<%=strDesc%>', // 分享描述
            link: '<%=pageurl%>', // 分享链接
            imgUrl: '<%=strImg%>', // 分享图标
            success: function () {
               
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
               
                // 用户取消分享后执行的回调函数
            }
        });
        //分享到腾讯微博
        wx.onMenuShareWeibo({
            title: '<%=title%>', // 分享标题
            desc: '<%=strDesc%>', // 分享描述
            link: '<%=pageurl%>', // 分享链接
            imgUrl: '<%=strImg%>', // 分享图标
            success: function () {
              
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
              
                // 用户取消分享后执行的回调函数
            }
        });
    });

注意事项:前台链接地址和后台加密的链接地址必须一样