微信分享操作JSSDK

来源:互联网 发布:java io流总结 编辑:程序博客网 时间:2024/05/16 10:02

使用jssdk域名要绑定吗?

jssdk必须绑定域名才能使用,绑定根域后,子域无需再做绑定即可正常使用jssdk。切记微信公众号绑定的是一级或二级域名。而且要与Config的url域名一致。

使用jssdk如何在本地做测试?

可临时绑定一个域名,比如:a.com,在本地的host文件中设置192.168.0.0. a.com,访问a.com进行开发测试,本地开发完成后再做迁移调整。

使用js widget没有响应?

请检查appkey是否与域名绑定并且是否审核通过。

jssdk无法授权?

这种情况一般弹出的授权窗口被浏览器拦截导致,将授权页添加信任站点即可。

在mobile里如何使用jssdk?

由于jssdk授权是使用的弹出窗口,而目前有些移动终端是不支持弹窗的,故而无法通过正常流程进行授权。 可通过自行进行授权得到access_token后,调用jssdk中的WB2.init(‘access_token’ : access_token);后,再进行使用parseCMD或js widget。

 

*生成签名错误?(一般出错都在这里) 错误提示:invalid signature

1,、确认签名算法正确

2、确认config中noncestr,timestamp与用以签名中的对应noncestr,timestamp一致

3、确认url是页面完整的url,包括Get参数部分

4、确认config中的appid与用来获取jsapi_ticket的appid一致

5、确保一定缓存access-token和jsapi_ticket

特别注意:你在利用参数生成签名的时候,要对所有待签名参数按照字段名的 ASCII 码从小到大排序(字典序)后,使用 URL 键值对的格式(即key1=value1&key2=value2…)拼接成字符串 string1。这里需要注意的是所有参数名均为小写字符。


Code



直接取的Config

        #region   //微信分享数据++GetConfig(string appid ,string AppSecret,string url)        public  string Get_Config(string appid, string token, string url)        {            string wx_config = "";            try            {                //string ACCESS_TOKEN = thisACCESS_TOKEN(appid, appsecret);                string JSAPI_TICKET = thisJSAPI_TICKET(token);                SHA1 sha = new SHA1CryptoServiceProvider();                string string1 = "jsapi_ticket=" + JSAPI_TICKET + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + (url.IndexOf('#') >= 0 ? url.Substring(0, url.IndexOf('#')) : url);                #region +++--------------------------------------生成签名                SHA1 shatwo = SHA1.Create();                ASCIIEncoding encode = new ASCIIEncoding();                byte[] by = encode.GetBytes(string1);                shatwo.ComputeHash(by);                string result = System.BitConverter.ToString(shatwo.Hash).Replace("-", "");                #endregion                wx_config = "wx.config({" +                 "debug: false," + // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。                 "appId: '" + appid + "'," + // 必填,公众号的唯一标识                 "timestamp:" + timestamp + "," + // 必填,生成签名的时间戳                 "nonceStr: '" + noncestr + "'," + // 必填,生成签名的随机串                 "signature: '" + result + "'," +// 必填,签名,见附录1                @" jsApiList: [         'checkJsApi',        'onMenuShareTimeline',        'onMenuShareAppMessage',        'onMenuShareQQ',        'onMenuShareWeibo',        'hideMenuItems',        'showMenuItems',        'hideAllNonBaseMenuItem',        'showAllNonBaseMenuItem',        'translateVoice',        'startRecord',        'stopRecord',        'onRecordEnd',        'playVoice',        'pauseVoice',        'stopVoice',        'uploadVoice',        'downloadVoice',        'chooseImage',        'previewImage',        'uploadImage',        'downloadImage',        'getNetworkType',        'openLocation',        'getLocation',        'hideOptionMenu',        'showOptionMenu',        'closeWindow',        'scanQRCode',        'chooseWXPay',        'openProductSpecificView',        'addCard',        'chooseCard',        'openCard'        ]" + // 必填,需要使用的JS接口列表,所有JS接口列表见附录2             "});";                return wx_config;            }            catch (Exception)            {                throw;            }        }        #region ..._+++方法        /// <summary>        /// 生成随机字母与数字        /// </summary>        /// <param name="Length">生成长度</param>        /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>        /// <returns></returns>        public static string Str(int Length, bool Sleep)        {            if (Sleep)                System.Threading.Thread.Sleep(3);            char[] Pattern = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; //, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };            string result = "";            int n = Pattern.Length;            System.Random random = new System.Random(~unchecked((int)System.DateTime.Now.Ticks));            for (int i = 0; i < Length; i++)            {                int rnd = random.Next(0, n);                result += Pattern[rnd];            }            return result;        }        public static string thisACCESS_TOKEN(string AppID, string AppSecret)        {            WebClient myWebClient = new WebClient();            byte[] myDataBuffer = myWebClient.DownloadData("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppID + "&secret=" + AppSecret);            string json = Encoding.UTF8.GetString(myDataBuffer);            JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类            ACCESS_TOKEN_Json list = js.Deserialize<ACCESS_TOKEN_Json>(json);    //将json数据转化为对象类型并赋值给list            string ACCESS_TOKEN = list.access_token;            return ACCESS_TOKEN;        }        /// <summary>        /// 当前Weixin  JSAPI_TICKET        /// </summary>        public static string thisJSAPI_TICKET(string ACCESS_TOKEN)        {            WebClient myWebClient = new WebClient();            byte[] myDataBuffer = myWebClient.DownloadData("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + ACCESS_TOKEN + "&type=jsapi");            string json = Encoding.UTF8.GetString(myDataBuffer);            JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类            JSAPI_TICKET_Json list = js.Deserialize<JSAPI_TICKET_Json>(json);    //将json数据转化为对象类型并赋值给list            string JSAPI_TICKET = list.ticket;            return JSAPI_TICKET;        }        /// <summary>        /// 获取授权的ACCESS_TOKEN        /// </summary>        public struct ACCESS_TOKEN_Json        {            public string access_token { get; set; }        }        /// 获取授权的JSAPI_TICKET        /// </summary>        public struct JSAPI_TICKET_Json        {            public string ticket { get; set; }        }        #endregion        #endregion



页面HTML 


        <%= wx_config %>        wx.ready(function(){            wx.showOptionMenu();          var dataForWeixin = {              imgUrl: "img/start.png",              link: "<%= Link %>" , //此Link一定是要截取的Linq不然会带openid              title:"分享数据,收获豪礼!",              desc: "我已成功参与了分享,如果你也想get百丽宫、SKII、各大餐厅……送出的礼物,点击进入游戏抢购属于自己的礼品!"        };                   //分享朋友圈         wx.onMenuShareTimeline({                title: dataForWeixin.title, // 分享标题                link: dataForWeixin.link, // 分享链接                imgUrl: dataForWeixin.imgUrl, // 分享图标                success: function () {                     // 用户确认分享后执行的回调函数                                            $.ajax({                        url: "lhjAct.ashx",                        dataType: "json",                        data: {                            openid: openid,                            myact: "updateshare",                            aid: aid,                            rad: Math.random()                        },                        success: function (data) {                      if(data.share>0){                       $("#mcover").show();                           share-=1;                       $("#pshare").html("亲,你需要分享"+share+"次才能激活领取奖品权限!")            }else            {                $("#mcover").hide();            }                        }                        });                                    },                cancel: function () {                     // 用户取消分享后执行的回调函数                }            });                      //分享给朋友            wx.onMenuShareAppMessage( {                title: dataForWeixin.title, // 分享标题                link: dataForWeixin.link, // 分享链接                imgUrl: dataForWeixin.imgUrl, // 分享图标                desc: dataForWeixin.desc, // 分享描述                               type: '', // 分享类型,music、video或link,不填默认为link                dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空                success: function () {                              $.ajax({                        url: "lhjAct.ashx",                        dataType: "json",                        data: {                            openid: openid,                            myact: "updateshare",                            aid: aid,                            rad: Math.random()                        },                        success: function (data) {                      if(data.share>0){                       $("#mcover").show();                       share-=1;                       $("#pshare").html("亲,你需要分享"+share+"次才能激活领取奖品权限!")//                       location.reload();            }else            {                $("#mcover").hide();            }                        }                        });                                     },                cancel: function () {                     // 用户取消分享后执行的回调函数                }            });


对了别忘了引用JS文件。

0 0