调用微信内置的方法及wx.config的配置问题
首先请看网址:
https://www.w3cschool.cn/weixinkaifawendang/h8ap1qe5.html
重点说下怎么配置wx.config(为了安全,所有的参数都在服务端获取)
var link = location.href; $.ajax({ url: "/WxJSSDK/WxJS_SDK.aspx/GetInfoMation",//后台给你提供的接口 type: "Post", data: "{ 'url': '"+link+"' }", async: false, contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var datad = JSON.parse(data.d); //转译为Json字符串 wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来 appId: datad.appid, // 必填,公众号的唯一标识 timestamp: datad.timestamp, // 必填,生成签名的时间戳 nonceStr: datad.noncestr, // 必填,生成签名的随机串 signature: datad.signature,// 必填,签名,见附录1 jsApiList: [ "openLocation" ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); wx.error(function (res) { layer.msg(res); }); }, error: function (error) { layer.msg(error) } });
访问的页面方法:
#region 获取AccessToken private static string GetAccessToken() { //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET string tokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", "client_credential", ConfigurationManager.AppSettings["appid"], ConfigurationManager.AppSettings["secret"]); var wc = new WebClient(); var strReturn = wc.DownloadString(tokenUrl);return strReturn; } #endregion #region 获取Jsapi_Ticket private static string GetWeiXinJsapi_Ticket(string accessToken) { string tokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type={1}", accessToken, "jsapi"); var wc = new WebClient(); var strReturn = wc.DownloadString(tokenUrl); //取得微信返回的json数据 return strReturn; } #endregion #region 基础字符 private static string[] strs = new string[] { "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", "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" }; #endregion #region 创建随机字符串 private static string CreatenNonce_str() { Random r = new Random(); var sb = new StringBuilder(); var length = strs.Length; for (int i = 0; i < 15; i++) { sb.Append(strs[r.Next(length - 1)]); } return sb.ToString(); } #endregion #region 创建时间戳 private static long CreatenTimestamp() { return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000; } #endregion #region 签名算法 /// <summary> /// 签名算法 ///本代码来自开源微信SDK项目:https://github.com/night-king/weixinSDK /// </summary> /// <param name="jsapi_ticket">jsapi_ticket</param> /// <param name="noncestr">随机字符串(必须与wx.config中的nonceStr相同)</param> /// <param name="timestamp">时间戳(必须与wx.config中的timestamp相同)</param> /// <param name="url">当前网页的URL,不包含#及其后面部分(必须是调用JS接口页面的完整URL)</param> /// <returns></returns> public static string GetSignature(string jsapi_ticket, string noncestr, long timestamp, string url, out string string1) { var string1Builder = new StringBuilder(); string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&") .Append("noncestr=").Append(noncestr).Append("&") .Append("timestamp=").Append(timestamp).Append("&") .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url); string1 = string1Builder.ToString();return FormsAuthentication.HashPasswordForStoringInConfigFile(string1, "SHA1"); } #endregion //GET api/GetInfoMation /// <summary> ///初始化的数据调用微信接口返回参数 /// </summary> /// <returns></returns> [WebMethod] public static string GetInfoMation(string url) { try { //生成tokcen string tocken = GetAccessToken(); JObject TokenJO = (JObject)JsonConvert.DeserializeObject(tocken); //验证签名 string Jsapi_Ticket = GetWeiXinJsapi_Ticket(TokenJO["access_token"].ToString()); JObject Jsapi_TicketJo = (JObject)JsonConvert.DeserializeObject(Jsapi_Ticket); #region string rtn = ""; string jsapi_ticket = Jsapi_TicketJo["ticket"].ToString(); string noncestr = CreatenNonce_str(); long timestamp = CreatenTimestamp(); string outstring = ""; string JS_SDK_Result = GetSignature(jsapi_ticket, noncestr, timestamp, url, out outstring); //拼接json串返回前台 rtn = "{\"appid\":\"" + ConfigurationManager.AppSettings["appid"] + "\",\"jsapi_ticket\":\"" + jsapi_ticket + "\",\"noncestr\":\"" + noncestr + "\",\"timestamp\":\"" + timestamp + "\",\"outstring\":\"" + outstring + "\",\"signature\":\"" + JS_SDK_Result.ToLower() + "\"}";#endregion return rtn; } catch (Exception ex) { return string.Empty; } }
调用接口方法(例如:打开地图):
//打开地图 function funOpenLocation(id) { var dataArray = [[40.036692, 116.425381, "北苑大酒店", "双营路12号 "], [40.020808, 116.433250, "北京会议中心", "北京市朝阳区来广营西路88号"], [39.818720, 119.505420, "国海宾馆", "河北省秦皇岛市北戴河东经路154号"]]; wx.openLocation({ latitude: dataArray[id][0], // 纬度,浮点数,范围为90 ~ -90 longitude: dataArray[id][1], // 经度,浮点数,范围为180 ~ -180。 name: dataArray[id][2], // 位置名 address: dataArray[id][3], // 地址详情说明 scale: 18, // 地图缩放级别,整形值,范围从1~28。默认为最大 infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转 }); }