标签:
微信接口开发,包含服务端(采用.net),前端js
//服务端 namespace EatWorld { public partial class Default : System.Web.UI.Page { string Token = System.Configuration.ConfigurationManager.AppSettings["Token"]; string appid = System.Configuration.ConfigurationManager.AppSettings["appid"]; string appsecret = System.Configuration.ConfigurationManager.AppSettings["appsecret"]; /// <summary> /// 用户登录验证 验证成功后返回用户json信息 /// </summary> public void User_Redirect_Uri() { if (!string.IsNullOrEmpty(Request["code"])) { string userCode = Request["code"].ToString(); string postStr = GetWXAPI_Data("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + userCode + "&grant_type=authorization_code"); WXUserInfo wxu = JsonConvert.DeserializeObject(postStr, typeof(WXUserInfo)) as WXUserInfo; Session["WXUserInfo"] = wxu; Session.Timeout = 60 * 2; WriteText(wxu.refresh_token); Response.Redirect("/PhoneCarmeor.htm?refresh_token=" + DateTime.Now.ToString("yyyy-MM-dd") + "|" + wxu.refresh_token); //Response.Write("<script>localStorage[‘refresh_token‘]=‘" + DateTime.Now.ToString("yyyy-MM-dd") + "|" + wxu.refresh_token + "‘;location.href=‘" + Request.Url + "‘;</script>"); } else { string refresh_token = Request["refresh_token"].ToString().Split(‘|‘)[0]; if (Session["WXUserInfo"] == null) { string postStr = GetWXAPI_Data("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appid + "&grant_type=refresh_token&refresh_token=" + refresh_token); WXUserInfo wxu = JsonConvert.DeserializeObject(postStr, typeof(WXUserInfo)) as WXUserInfo; Session["WXUserInfo"] = wxu; } WXUserInfo.UserInfo = Session["WXUserInfo"] as WXUserInfo; string postUserStr = GetWXAPI_Data("https://api.weixin.qq.com/sns/userinfo?access_token=" + WXUserInfo.UserInfo.access_token + "&openid=" + WXUserInfo.UserInfo.openid + "&lang=zh_CN"); WXUserInfo.UserDetailed = JsonConvert.DeserializeObject(postUserStr, typeof(WXUserDetailed)) as WXUserDetailed; Response.Clear(); Response.Write(JsonConvert.SerializeObject(WXUserInfo.UserDetailed)); Response.End(); Response.Flush(); } } /// <summary> /// 创建全局Token文件 并且返回Token /// </summary> /// <param name="pamFileUrl"></param> /// <param name="pamSeconds"></param> /// <param name="pamAccessToken"></param> public string CreateAccessToken(string pamFileUrl, string pamColumnName) { //文件存放地址 pamFileUrl = Server.MapPath(pamFileUrl); //当前操作 string Operating = "Add"; //数据集 DataSet ds = new DataSet(); //如果磁盘存在此文件则直接加载到数据集上 否则 就重新创建 if (!File.Exists(pamFileUrl)) ds = new Access_Token(); else ds.ReadXml(pamFileUrl); //筛选当前数据集中ColumnName是当前key的行 DataView dv = ds.Tables[0].DefaultView; dv.RowFilter = "ColumnName=‘" + pamColumnName + "‘ and ColumnValue<>‘‘"; DataRow dr = null; //判断是否找到当前ColumnName的行 如果有 临时认为是修改 否则是添加 if (dv.Count > 0) { dr = dv[0].Row; Operating = "Update"; } else dr = ds.Tables[0].NewRow(); //获取当前时间 DateTime nowdatetime = DateTime.Now; DateTime enddatetime = DateTime.Now; //如果是修改的话 则取出当前行中的时间 if (Operating == "Update") enddatetime = new DateTime(long.Parse(dr[1].ToString())); //获取当前时间和修改时间的差 TimeSpan nowtimespan = new TimeSpan(nowdatetime.Ticks); TimeSpan endtimespan = new TimeSpan(enddatetime.Ticks); TimeSpan timespan = nowtimespan.Subtract(endtimespan).Duration(); //操作为添加或者生成的值失效后触发 if (Operating == "Add" || timespan.TotalSeconds >= 7200) { //定义变量 获取当前秒, //和从微信API中获取的值一并保存到文件中, //用来检测是否已失效 long pamSeconds = DateTime.Now.Ticks; //访问微信API接口返回的值 string postStr = ""; //微信反馈信息临时储存类 WXHelper helper; //把当前秒和ColumnName加到文件里 dr[1] = pamSeconds; dr[0] = pamColumnName; //根据获取ColumnName名称 访问相应的接口 并存储相应的值 switch (pamColumnName) { case "globle_access_token": postStr = GetWXAPI_Data("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret); helper = Newtonsoft.Json.JsonConvert.DeserializeObject(postStr, typeof(WXHelper)) as WXHelper; dr[2] = helper.access_token; break; case "jsapi_ticket": postStr = GetWXAPI_Data("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + Request["ACCESS_TOKEN"].ToString() + "&type=jsapi"); helper = Newtonsoft.Json.JsonConvert.DeserializeObject(postStr, typeof(WXHelper)) as WXHelper; dr[2] = helper.ticket; break; } if (Operating == "Update") { ds.Tables[0].AcceptChanges(); ds.WriteXml(pamFileUrl, XmlWriteMode.WriteSchema); } else { ds.Tables[0].Rows.Add(dr); ds.WriteXml(pamFileUrl, XmlWriteMode.WriteSchema); } } //返回当前接口返回的值 return dr[2].ToString(); } /// <summary> /// 根据地址远程访问web服务器 /// </summary> /// <param name="pamUrl">要访问的地址</param> /// <returns></returns> public string GetWXAPI_Data(string pamUrl) { WebRequest webReq = WebRequest.Create(pamUrl); //接收远程WEB服务器发回的响应 WebResponse webRes = webReq.GetResponse(); //获取文件长度 long fileLength = webRes.ContentLength; //创建一个文件流,接收返回的流信息 Stream srm = webRes.GetResponseStream(); //使用特殊编码读取流信息 StreamReader srmReader = new StreamReader(srm); //定义缓冲区 byte[] bufferbyte = new byte[fileLength]; //缓冲区长度 int allByte = (int)bufferbyte.Length; int startByte = 0; //读取缓冲区内容 while (fileLength > 0) { int downByte = srm.Read(bufferbyte, startByte, allByte); if (downByte == 0) { break; }; startByte += downByte; allByte -= downByte; } string postStr = Encoding.UTF8.GetString(bufferbyte); return postStr; } protected void Page_Load(object sender, EventArgs e) { WriteText("开放平台进来了!\r\n"); WriteText(Request.HttpMethod.ToLower()); if (!string.IsNullOrEmpty(Request["Method"])) { switch (Request["Method"].ToString()) { case "createToken": if (!Directory.Exists(Server.MapPath("/CDT/XML"))) Directory.CreateDirectory(Server.MapPath("/CDT/XML")); string token = CreateAccessToken("/CDT/XML/Access_Token.xml", "globle_access_token"); Response.Clear(); Response.Write(token); Response.End(); Response.Flush(); break; case "getJsapi_ticket": if (!Directory.Exists(Server.MapPath("/CDT/XML"))) Directory.CreateDirectory(Server.MapPath("/CDT/XML")); string jsapi_ticket = CreateAccessToken("/CDT/XML/Access_Token.xml", "jsapi_ticket"); Response.Clear(); Response.Write(jsapi_ticket); Response.End(); Response.Flush(); break; case "User_Redirect_Uri": User_Redirect_Uri(); break; case "login": Valid(); break; } } if (IsPostBack) return; string postStr = ""; if (Request.HttpMethod.ToLower() == "post") { Stream s = System.Web.HttpContext.Current.Request.InputStream; byte[] b = new byte[s.Length]; s.Read(b, 0, (int)s.Length); postStr = Encoding.UTF8.GetString(b); WriteText("开始"); if (!string.IsNullOrEmpty(postStr)) { WriteText("进来了1"); //封装请求类 XmlDocument doc = new XmlDocument(); doc.LoadXml(postStr); XmlElement rootElement = doc.DocumentElement; XmlNode MsgType = rootElement.SelectSingleNode("MsgType"); WxUser.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText; WxUser.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText; WxUser.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText; WxUser.MsgType = MsgType.InnerText; WriteTxt("----------粉丝发送过来的消息,消息类型:" + WxUser.MsgType + "----------:" + WxUser.FromUserName); if (WxUser.MsgType == "text") { WxUser.Content = rootElement.SelectSingleNode("Content").InnerText; WxUser.MsgId = rootElement.SelectSingleNode("MsgId").InnerText; WriteText(rootElement.SelectSingleNode("Content").InnerText); ResponseMsg(); } else if (WxUser.MsgType == "location") { WxUser.Location_X = rootElement.SelectSingleNode("Location_X").InnerText; WxUser.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText; WxUser.Scale = rootElement.SelectSingleNode("Scale").InnerText; WxUser.Label = rootElement.SelectSingleNode("Label").InnerText; } else if (WxUser.MsgType == "image") { WxUser.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText; ResponseMsg(); } else if (WxUser.MsgType == "event") { WxUser.Wxevent = rootElement.SelectSingleNode("Event").InnerText; WxUser.EventKey = rootElement.SelectSingleNode("EventKey").InnerText; } //WriteText("我终于获取到用户的openid了 哈哈哈 这是FromUserName: " + user.FromUserName + " ,这是ToUserName: " + user.ToUserName); //Response.Write("<script>alert(‘" + user.ToUserName + "‘);</script>"); //WxUser u = Session["WxUser"] as WxUser; //WriteTxt("----------粉丝发送过来的消息,消息类型:" + u.MsgType + "----------:" + u.ToUserName); //Session["UserId"] = string UserId = FuncUser_CDS.FuncUser_CreateOne(WxUser.FromUserName, "", "", "", 0); WxUser.UserId = Convert.ToInt32(UserId); //Session["UserId"] = WxUser.UserId; //WriteText("UserIdDown1:" + UserId); //Response.Write("<script>alert(‘" + UserId + "‘);return;</script>"); WriteText("进来了"); } } else { Response.Write("没进来"); //Valid(); } if (!string.IsNullOrEmpty(WxUser.UserId.ToString()) && WxUser.UserId > 0) { SessionWx.Add(WxUser.FromUserName, WxUser.UserId); } //WriteText(WxUser.FromUserName + ",UserId=" + UserId); if (WxUser.FromUserName != "") { //NavType= if (!string.IsNullOrEmpty(Request["NavType"])) { switch (Request["NavType"]) { case "BusinessView": Response.Redirect("/Business_View.html?BusinessKey=" + Request["BusinessKey"]); break; } } else { Response.Redirect("/Business_List.html"); } } //} //Response.Write("<script>alert(‘抱歉,因为网络问题获取用户资料失败!请重新点餐!‘);return;</script>"); } /// <summary> /// 调试写入文件 /// </summary> /// <param name="context"></param> public void WriteText(string context) { FileStream fs = new FileStream(Server.MapPath("/TextFile1.txt").ToString(), FileMode.Append); StreamWriter sw = new StreamWriter(fs, Encoding.UTF8); sw.Write(context); sw.Close(); fs.Close(); } /// <summary> /// 验证微信签名 /// </summary> /// * 将token、timestamp、nonce三个参数进行字典序排序 /// * 将三个参数字符串拼接成一个字符串进行sha1加密 /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。 /// <returns></returns> private bool CheckSignature() { string signature = Request.QueryString["signature"]; string timestamp = Request.QueryString["timestamp"]; string nonce = Request.QueryString["nonce"]; string[] ArrTmp = { Token, timestamp, nonce }; Array.Sort(ArrTmp); //字典排序 string tmpStr = string.Join("", ArrTmp); tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); tmpStr = tmpStr.ToLower(); if (tmpStr == signature) { return true; } else { return false; } } private void Valid() { string echoStr = Request.QueryString["echoStr"]; if (CheckSignature()) { if (!string.IsNullOrEmpty(echoStr)) { Response.Clear(); Response.Write(echoStr); Response.Flush(); Response.End(); } } } /// <summary> /// 回复消息(微信信息返回) /// </summary> /// <param name="weixinXML"></param> private void ResponseMsg(/*WxUser user*/) { string resxml = "<xml><ToUserName><![CDATA[" + WxUser.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + WxUser.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime>"; try { if (WxUser.MsgType == "text") { int count = 0; if (WxUser.Content.Trim() == "单图") { count = 1; resxml += "<MsgType><![CDATA[news]]></MsgType><ArticleCount>" + count + "</ArticleCount><Articles>"; resxml += "<item><Title><![CDATA[这里是标题]]></Title><Description><![CDATA[这里是描述,当是单图文的时候描述才会展示]]></Description><PicUrl><![CDATA[http://imgsrc.baidu.com/product_name/pic/item/32374836acaf2edd470a31508d1001e93801934a.jpg]]></PicUrl><Url><![CDATA[http://www.baidu.com]]></Url></item>";//URL是点击之后跳转去那里,这里跳转到百度 resxml += "</Articles><FuncFlag>0</FuncFlag></xml>"; } else if (WxUser.Content.Trim() == "多图") { count = 10; resxml += "<MsgType><![CDATA[news]]></MsgType><ArticleCount>" + count + "</ArticleCount><Articles>"; for (int i = 0; i < count; i++) { resxml += "<item><Title><![CDATA[这里是标题" + (i + 1) + "]]></Title><Description><![CDATA[这里是描述,当是单图文的时候描述才会展示]]></Description><PicUrl><![CDATA[http://imgsrc.baidu.com/product_name/pic/item/32374836acaf2edd470a31508d1001e93801934a.jpg]]></PicUrl><Url><![CDATA[http://www.baidu.com]]></Url></item>";//URL是点击之后跳转去那里,这里跳转到百度 } resxml += "</Articles><FuncFlag>0</FuncFlag></xml>"; } else { if (WxUser.Content == "1234") { resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[http://17haidai.cn/IFrame_Jb.htm]]></Content><FuncFlag>0</FuncFlag></xml>"; WriteText("\n\n返回给粉丝的消息:" + resxml); System.Web.HttpContext.Current.Response.Write(resxml); System.Web.HttpContext.Current.Response.End(); Response.End(); } } } else if (WxUser.MsgType == "location") { resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你发过来的是地理消息\n哈哈]]></Content><FuncFlag>0</FuncFlag></xml>"; } else if (WxUser.MsgType == "image") { resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你发一张图片过来我怎么识别啊,你以为我有眼睛啊\n哈哈]]></Content><FuncFlag>0</FuncFlag></xml>"; } else if (WxUser.MsgType == "event") { if (WxUser.Wxevent == "unsubscribe") { //取消关注 } else { //新增关注 resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[谢谢你关注我。]]></Content><FuncFlag>0</FuncFlag></xml>"; } } } catch (Exception ex) { WriteTxt("异常:" + ex.Message); } DataView dv = ReplyTemp_CDS.ReplyTemp_ByKeyWordGet(WxUser.Content).Tables[0].DefaultView; if (dv.Count > 0) { StringBuilder sb = new StringBuilder(); sb.Append(" <xml> "); sb.Append(" <ToUserName><![CDATA[" + WxUser.FromUserName + "]]></ToUserName> "); sb.Append(" <FromUserName><![CDATA[" + WxUser.ToUserName + "]]></FromUserName> "); sb.Append(" <CreateTime>" + WxUser.CreateTime + "</CreateTime> "); sb.Append(" <MsgType><![CDATA[news]]></MsgType> "); sb.Append(" <ArticleCount>1</ArticleCount> "); sb.Append(" <Articles> "); sb.Append(" <item> "); sb.Append(" <Title><![CDATA[" + dv[0]["TempTitle"].ToString() + "]]></Title> "); sb.Append(" <Description><![CDATA[" + dv[0]["TempContent"].ToString() + "]]></Description> "); sb.Append(" <PicUrl><![CDATA[http://eat.onkm.net/asd/" + dv[0]["BusinessKey"].ToString() + "/ReplyTemp/img/" + dv[0]["TempId"].ToString() + "." + ((enmHasPic)dv[0]["TempExtend"]).ToString() + "]]></PicUrl>"); //sb.Append(" <PicUrl><![CDATA[http://eat.onkm.net/asd/GLMyinyuect/ReplyTemp/img/1.jpg]]></PicUrl>"); WriteText(dv[0]["TempExtend"].ToString()); string pamTempUrl = Convert.ToInt32(dv[0]["TempType"]) == Convert.ToInt32(enmReplyTempType.内部链接) ? "http://eat.onkm.net/Default.aspx?BusinessKey=" + dv[0]["BusinessKey"].ToString() + "&TypeId=0&NavType=BusinessView" : dv[0]["TempUrl"].ToString(); sb.Append(" <Url><![CDATA[" + pamTempUrl + "]]></Url> "); sb.Append(" </item> "); sb.Append(" </Articles> "); sb.Append(" </xml> "); System.Web.HttpContext.Current.Response.Write(sb.ToString()); System.Web.HttpContext.Current.Response.End(); Response.End(); } } /// <summary> /// unix时间转换为datetime /// </summary> /// <param name="timeStamp"></param> /// <returns></returns> private DateTime UnixTimeToTime(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } /// <summary> /// datetime转换为unixtime /// </summary> /// <param name="time"></param> /// <returns></returns> private int ConvertDateTimeInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return (int)(time - startTime).TotalSeconds; } /// <summary> /// 记录bug,以便调试 /// </summary> /// /// <returns></returns> public bool WriteTxt(string str) { try { FileStream fs = new FileStream(Server.MapPath("/bugLog.txt"), FileMode.Append); StreamWriter sw = new StreamWriter(fs); //开始写入 sw.WriteLine(str); //清空缓冲区 sw.Flush(); //关闭流 sw.Close(); fs.Close(); } catch (Exception) { return false; } return true; } } //微信请求类 /// <summary> /// 微信请求类 /// </summary> public class WeiXinRequest { private string toUserName; /// <summary> /// 消息接收方微信号,一般为公众平台账号微信号 /// </summary> public string ToUserName { get { return toUserName; } set { toUserName = value; } } private string fromUserName; /// <summary> /// 消息发送方微信号 /// </summary> public string FromUserName { get { return fromUserName; } set { fromUserName = value; } } private string createTime; /// <summary> /// 创建时间 /// </summary> public string CreateTime { get { return createTime; } set { createTime = value; } } private string msgType; /// <summary> /// 信息类型 地理位置:location,文本消息:text,消息类型:image,音频:voice,视频:video,取消关注:Action /// </summary> public string MsgType { get { return msgType; } set { msgType = value; } } private string content; /// <summary> /// 信息内容 /// </summary> public string Content { get { return content; } set { content = value; } } private string msgId; /// <summary> /// 消息ID(文本) /// </summary> public string MsgId { get { return msgId; } set { msgId = value; } } private string wxevent; /// <summary> /// 取消关注时的Event节点 /// </summary> public string Wxevent { get { return wxevent; } set { wxevent = value; } } private string eventKey; /// <summary> /// 取消关注时的EventKey节点 /// </summary> public string EventKey { get { return eventKey; } set { eventKey = value; } } private string location_X; /// <summary> /// 地理位置纬度 /// </summary> public string Location_X { get { return location_X; } set { location_X = value; } } private string location_Y; /// <summary> /// 地理位置经度 /// </summary> public string Location_Y { get { return location_Y; } set { location_Y = value; } } private string scale; /// <summary> /// 地图缩放大小 /// </summary> public string Scale { get { return scale; } set { scale = value; } } private string label; /// <summary> /// 地理位置信息 /// </summary> public string Label { get { return label; } set { label = value; } } private string picUrl; /// <summary> /// 图片链接,开发者可以用HTTP GET获取 /// </summary> public string PicUrl { get { return picUrl; } set { picUrl = value; } } }
//前端
WX_Login: function (sucessUrl) { if ((Request["code"] == "" || Request["code"] == null || Request["code"] == undefined)) location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + sky.params.appid + "&redirect_uri=" + encodeURIComponent("http://17haidai.cn/IFrame_Jb.htm?successurl=" + sucessUrl + "&BusinessKey=" + scope.BusinessKey + (Request["navType"] != null && Request["navType"] != undefined ? "&navType=share" : "") + "&TypeParent=" + (scope.TypeParent == undefined ? "" : scope.TypeParent)) + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; else $.get("/ase/WXLogin.ashx", { "Method": "Get_UserInfo", "Wx_Method": "user_access_token", "code": Request["code"] }, function (msg) { msg = eval("[" + msg + "]"); sky.setCookie("user_access_token", msg[0].access_token, 24); sky.setCookie("user_refresh_token", msg[0].refresh_token, 720); sky.setCookie("user_openId", msg[0].openid, 24); }); }, Get_User_Access_Token: function () { $.get("/ase/WXLogin.ashx", { "Method": "Get_UserInfo", "Wx_Method": "user_refresh_token", "user_refresh_token": sky.getCookie("user_refresh_token") }, function (msg) { msg = eval("[" + msg + "]"); sky.setCookie("user_access_token", msg[0].access_token, 24); sky.setCookie("user_refresh_token", msg[0].refresh_token, 720); sky.setCookie("user_openId", msg[0].openid, 24); }); }, Get_Globle_Access_Token: function () { if (sky.getCookie("globle_access_token") == "") { $.get("/ase/WXLogin.ashx", { "Method": "Get_UserInfo", "Wx_Method": "globle_access_token" }, function (msg) { msg = eval("[" + msg + "]"); sky.setCookie("globle_access_token", msg[0].access_token, 2); sky.Get_Jsapi_Ticket(); }); } else sky.Get_Jsapi_Ticket(); }, Get_Jsapi_Ticket: function () { if (sky.getCookie("jsapi_ticket") == "") $.get("/ase/WXLogin.ashx", { "Method": "Get_UserInfo", "Wx_Method": "jsapi_ticket", "globle_access_token": sky.getCookie("globle_access_token") }, function (msg) { msg = eval("[" + msg + "]"); sky.setCookie("jsapi_ticket", msg[0].ticket, 2); sky.WX_Js_Valid(sky.getCookie("jsapi_ticket")); }); else sky.WX_Js_Valid(sky.getCookie("jsapi_ticket")); }, WX_Js_Valid: function (jsapi_ticket) { var qm = sign(jsapi_ticket, location.href); wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: sky.params.appid, // 必填,公众号的唯一标识 timestamp: qm.timestamp, // 必填,生成签名的时间戳 nonceStr: qm.nonceStr, // 必填,生成签名的随机串 signature: qm.signature, // 必填,签名,见附录1 jsApiList: [‘onMenuShareAppMessage‘, ‘onMenuShareTimeline‘, ‘previewImage‘] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); }, getCookie: function (c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "=") if (c_start != -1) { c_start = c_start + c_name.length + 1 c_end = document.cookie.indexOf(";", c_start) if (c_end == -1) c_end = document.cookie.length return unescape(document.cookie.substring(c_start, c_end)) } } return ""; }, setCookie: function (c_name, value, expiredays) { var exdate = new Date(); exdate.setHours(exdate.getHours() + expiredays); document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) },//调用微信js准备方法 Wx_JSRead: function (pamTitle, pamImgUrl, pamLink, pamDesp) { //当微信js验证成功后触发此函数 wx.ready(function () { // $(".loading").hide(); wx.onMenuShareTimeline({ title: pamTitle, // 分享标题 link: pamLink, // 分享链接 imgUrl: pamImgUrl, // 分享图标 trigger: function (res) { //alert(‘用户点击分享到朋友圈‘); }, success: function () { var sky_initComplete = setInterval(function () { clearInterval(sky_initComplete); sky.Alter("您已分享到朋友圈!"); var Alter_Inver = setTimeout(function () { clearInterval(Alter_Inver); $(".sky_alter .sky_alter_close").click(); }, 1000); }, 1); // alert("分享朋友圈成功"); // 用户确认分享后执行的回调函数 }, cancel: function () { // 用户取消分享后执行的回调函数 }, fail: function (res) { //alert(‘wx.onMenuShareTimeline:fail: ‘ + JSON.stringify(res)); } }); // pamTitle = "能帮您快速定位附近商家,查看商家详情、楼层图、所售品牌、规划路线,助您在海外旅行时快速找到想要的商家,是您海外旅行的必备好帮手。"; wx.onMenuShareAppMessage({ title: pamTitle, // 分享标题 desc: pamDesp, // 分享描述 link: pamLink, // 分享链接 imgUrl: pamImgUrl, // 分享图标 type: ‘link‘, // 分享类型,music、video或link,不填默认为link success: function () { // 用户确认分享后执行的回调函数 }, cancel: function () { // 用户取消分享后执行的回调函数 } }); }); }
标签:
原文地址:http://www.cnblogs.com/fxnet/p/5910284.html