.net 微信分享功能

     微信在国内目前无疑是最火的社交软件,智能手机装机必备。

     微信api有java,php,Python语言的demo, 为毛没有C#的范例?兄长今天给各位带来一个。不叫哥(割)了,A股今天又暴跌【3912.77 -140.93 (-3.48%)】,为国满仓中...

    1.微信帮助类:

    

 public class WeChatHelper
    {
        /// <summary>
        /// 公众号的全局唯一票据
        /// </summary>
        public static String ACCESS_TOKEN = null;
        /// <summary>
        /// 凭证有效时间7200秒
        /// </summary>
        public static DateTime? ACCESS_TOKEN_EXPIRE_TIME = null;
        /// <summary>
        /// 公众号用于调用微信JS接口的临时票据
        /// </summary>
        public static String JS_API_TICKET = null;
        /// <summary>
        /// 有效期为7200秒
        /// </summary>
        public static DateTime? JS_API_TICKET_EXPIRE_TIME = null;
    
        public const  String  APP_ID = "你的";
        public const String APP_SECRET = "你的";
        /// <summary>
        /// 生成签名的随机串
        /// </summary>
        private String nonce = null;
        /// <summary>
        /// 生成签名的时间戳
        /// </summary>
        private String timestamp = null;
        /// <summary>
        /// 签名
        /// </summary>
        private String signature = null;
        /// <summary>
        /// 当前网页的URL,不包含#及其后面部分
        /// </summary>
        private String url = null;

        public WeChatHelper(string url)
        {
            this.url = url;
            this.CheckAccessTokenAndJsApiTicket();
            if (JS_API_TICKET == null || JS_API_TICKET.Trim().Length < 0)
            {
                throw new Exception("JS_API_TICKET is empty.");
            }
            this.Sign();
        }

        private void CheckAccessTokenAndJsApiTicket()
        {
            DateTime now = DateTime.Now;

            if (ACCESS_TOKEN == null || ACCESS_TOKEN_EXPIRE_TIME == null || now > ACCESS_TOKEN_EXPIRE_TIME)
            {
                this.initAccessToken();
            }

            if (JS_API_TICKET == null || JS_API_TICKET_EXPIRE_TIME == null || now > JS_API_TICKET_EXPIRE_TIME)
            {
                this.initJSAPITicket();
            }
        }
        /// <summary>
        /// 初始化凭证
        /// </summary>
        private void initAccessToken()
        {
            String result = "";
            try {
                 DateTime expireTime = DateTime.Now;
             
                 String accessURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
                 Uri realUrl = new Uri(accessURL);
                 WebRequest request = WebRequest.Create(realUrl);
                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                 
                 using (Stream resStream = response.GetResponseStream())
                 {
                     if (resStream != null)
                     {
                         StreamReader reader = new StreamReader(resStream, Encoding.Default);
                         result = reader.ReadToEnd();
                     }
                     if (resStream != null) resStream.Close();
                 }

             
                 JavaScriptSerializer jss = new JavaScriptSerializer();
                 Dictionary<string, object> respDic = (Dictionary<string, object>)jss.DeserializeObject(result);
                 //var errCode = respDic["errcode"];
                 //var errMsg = respDic["errmsg"];
                 if (respDic.ContainsKey("errcode"))
                 {
                     throw new Exception("Fail to get weixin access token. ERROR Code:" + respDic["errcode"].ToString() + "  errMsg:" + respDic["errmsg"].ToString());
                 }
                 //通过键access_token获取值
                 ACCESS_TOKEN = respDic["access_token"].ToString();
                 var expireIn = respDic["expires_in"];
                 if (expireIn != null){
                     expireTime = expireTime.AddSeconds(double.Parse(expireIn.ToString()));
                 }

                 ACCESS_TOKEN_EXPIRE_TIME = expireTime;

            }finally{
                
            }
        }
        /// <summary>
        /// 初始临时票据
        /// </summary>
        private void initJSAPITicket()
        {
            String result = "";
            try {
                 DateTime expireTime = DateTime.Now;
             
                 String accessURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + ACCESS_TOKEN + "&type=jsapi";

                 Uri realUrl = new Uri(accessURL);
                 WebRequest request = WebRequest.Create(realUrl);
                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                 using (Stream resStream = response.GetResponseStream())
                 {
                     if (resStream != null)
                     {
                         StreamReader reader = new StreamReader(resStream, Encoding.Default);
                         result = reader.ReadToEnd();
                     }
                     if (resStream != null) resStream.Close();
                 }
             
                 JavaScriptSerializer jss = new JavaScriptSerializer();
                 Dictionary<string, object> respDic = (Dictionary<string, object>)jss.DeserializeObject(result);

                 //var errCode = respDic["errcode"];
                 //var errMsg = respDic["errmsg"];

                 if (respDic.ContainsKey("errcode") && respDic["errcode"].ToString() != "0")
                 {
                     throw new Exception("Fail to get weixin access token. ERROR Code:" + respDic["errcode"].ToString() + "  errMsg:" + respDic["errmsg"].ToString());
                 }
             
                 JS_API_TICKET = respDic["ticket"].ToString();
                 var expireIn = respDic["expires_in"];

                 if (expireIn != null){
                     expireTime = expireTime.AddSeconds(double.Parse(expireIn.ToString()));
                 }

                 JS_API_TICKET_EXPIRE_TIME = expireTime;

            }finally{
                
            }
        }

        private void Sign()
        {
            this.nonce = Guid.NewGuid().ToString();
            this.timestamp = ((long)((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds/1000)).ToString();

            String signatureUnCrpty = "jsapi_ticket=" + JS_API_TICKET +
                    "&noncestr=" + this.nonce +
                    "&timestamp=" + this.timestamp +
                    "&url=" + this.url;

            this.signature = FormsAuthentication.HashPasswordForStoringInConfigFile(signatureUnCrpty, "SHA1");
        }

        public String getNonce()
        {
            return nonce;
        }

        public void setNonce(String nonce)
        {
            this.nonce = nonce;
        }

        public String getTimestamp()
        {
            return timestamp;
        }

        public void setTimestamp(String timestamp)
        {
            this.timestamp = timestamp;
        }

        public String getSignature()
        {
            return signature;
        }

        public void setSignature(String signature)
        {
            this.signature = signature;
        }

        public String getUrl()
        {
            return url;
        }

        public void setUrl(String url)
        {
            this.url = url;
        }
    }

2.前端脚本:wechat.js

  需要引入    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js" type="text/javascript" ></script>

var titleStr = '测一测,你是哪个小升初名校的菜';
var descStr = '测一测,你是哪个小升初名校的菜';
var linkStr = window.location.href;
var logoStr = 'http://game.zy.com/Content/images/share_icon.png';
var optionTimeline = {
    title: titleStr,
    desc: descStr,
    link: linkStr,
    imgUrl: logoStr,
    trigger: function (res) {
        //alert('用户点击分享到朋友圈');
    },
    success: function (res) {
        //alert('已分享');可以统计分享到朋友圈次数
        $.ajax({
            url: '/Game/SetShare',
            type: 'POST',
            async: false,
            cache: false,
            data: { typeID: 1 },
            success: function (objJson) {

            }
        });
    }
};
var optionAppMessag ={
            title: titleStr,
            desc: descStr,
            link: linkStr,
            imgUrl: logoStr,
            trigger: function (res) {
                //alert('用户点击发送给朋友');
            },
            success: function (res) {
                //alert('已分享');可以统计发送朋友次数
                $.ajax({
                    url: '/Game/SetShare',
                    type: 'POST',
                    async: false,
                    cache: false,
                    data: { typeID: 2 },
                    success: function (objJson) {

                    }
                });
            },
            cancel: function (res) {
                //alert('已取消');
            },
            fail: function (res) {
                //alert(JSON.stringify(res));
            }
        };
function getWeChat() {
    $.ajax({
        url: '/Game/GetWeChatInfo',
        type: 'GET',
        async: false,
        cache: false,
        data: { 'url': linkStr },
        success: function (objJson) {
            //            if (objJson.success) {
            var objJson = eval('(' + objJson + ')'); //由JSON字符串转换为JSON对象
            var appId = objJson.APP_ID;
            var timestamp = objJson.TIMESTAMP;
            var nonce = objJson.NONCE;
            var signature = objJson.SIGNATURE;
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: appId, // 必填,公众号的唯一标识
                timestamp: timestamp, // 必填,生成签名的时间戳
                nonceStr: nonce, // 必填,生成签名的随机串
                signature: signature, // 必填,签名,见附录1
                jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
            });
            //            }
            //            else { 

            //            }
        }

    });

}
//初始分享数据
function weChatShare(optionAppMessag, optionTimeline) {
    wx.ready(function () {
        wx.onMenuShareAppMessage(optionAppMessag);
        wx.onMenuShareTimeline(optionTimeline);
    })
};
wx.error(function(res){
    //alert("Error weixin");
    // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。

});
getWeChat();
weChatShare(optionAppMessag, optionTimeline);

 以上代码封装了相关参数,原因是 weChatShare() 方法初始了分享的标题,如果要使用动态的标题,必须在获取动态数据后在初始化一次。

 /* 游戏结束调用 返回答题的json */
            window.gameOver = function (strJson) {

                $.ajax({
                    url: "/Game/SumbmitAnswer",
                    type: "POST",
                    data: { answer: strJson },
                    timeout: 5000,
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        /* 更新视图 */
                        if (jc.hasUI("results")) {
                            jc.ui.results.all(function (i, obj) {
                                obj.setInfo({ scrollName: result.School, right: result.RightNum, ranking: result.Beat });
                                //初始化微信分享新数据
                                optionTimeline.title = optionAppMessag.title = "我答对了" + result.RightNum + "道题,打败了" + result.Beat + "%的学生,成为" + result.School + "学校的潜力学生. 放学后别走,等你来挑战";
                                weChatShare(optionAppMessag, optionTimeline);
                            });
                        }
                    }
                });

            }
原文地址:https://www.cnblogs.com/liuxiutianxia/p/4616663.html