微信开发笔记:对接微信JS-SDK
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html
第一步微信公众号配置:

第二步编写在ashx文件中编写WechartInterface方法如下:
<%@ WebHandler Language="C#" Class="api" Debug="true" %> using System; using System.IO; using System.Web; using System.Data; using System.Collections; using System.Collections.Generic; using System.Data.SqlClient; using System.Web.SessionState; using System.Text; using System.Text.RegularExpressions; using System.Configuration; using System.Net; using System.Web.Extensions; using System.Web.Script; using System.Web.Script.Serialization; using System.Web.Security; public class api:IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType="text/plain"; context.Response.AddHeader("Access-Control-Allow-Origin","*"); string type = context.Request["action"]; switch(type) { case "WechartInterface": WechartInterface(context); break; default: context.Response.Write("无效参数"); break; } context.Response.End(); } public void WechartInterface(HttpContext context) { JSSDk_Helper.WechartInterface(context); } public bool IsReusable { get { return false; } } } //JSSDk_Helper public static class JSSDk_Helper { public static string AppID="", AppSecret=""; public static string token=""; #region 微信公众号 服务器配置,验证token public static void WechartInterface(HttpContext context){ context.Response.ContentType = "text/plain"; string echoString = context.Request.QueryString["echoStr"]; string signature = context.Request.QueryString["signature"]; string timestamp = context.Request.QueryString["timestamp"]; string nonce = context.Request.QueryString["nonce"]; if (CheckSignature(token, signature, timestamp, nonce)){ if (!string.IsNullOrEmpty(echoString)){ context.Response.Write(echoString); context.Response.End(); } } } /// <summary> /// 验证微信签名 /// </summary> public static bool CheckSignature(string token, string signature, string timestamp, string nonce){ string[] ArrTmp = { token, timestamp, nonce }; //字典排序 Array.Sort(ArrTmp); //拼接 string tmpStr = string.Join("", ArrTmp); //sha1验证 tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); tmpStr = tmpStr.ToLower(); if (tmpStr == signature){ return true; }else{ return false; } } #endregion }
第三步编写wx.config:JS如下:
$.ajax({ url: '/api.ashx?type=GetWxJsApiConfig&url=' + escape(window.location.href), type: 'post', data: {}, dataType: 'json', success: function (data) { wx.config({ debug: false, appId: data.appId, timestamp: data.timestamp, nonceStr: data.nonceStr, signature: data.signature, jsApiList: [ 'checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'translateVoice', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'onVoicePlayEnd', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard' ] }); } });
第四步编写wx.config:asxh后台如下:
<%@ WebHandler Language="C#" Class="api" Debug="true" %> using System; using System.IO; using System.Web; using System.Data; using System.Collections; using System.Collections.Generic; using System.Data.SqlClient; using System.Web.SessionState; using System.Text; using System.Text.RegularExpressions; using System.Configuration; using System.Net; using System.Web.Extensions; using System.Web.Script; using System.Web.Script.Serialization; using System.Web.Security; public class api:IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType="text/plain"; context.Response.AddHeader("Access-Control-Allow-Origin","*"); string type = context.Request["action"]; switch(type) { case "GetWxJsApiConfig": GetWxJsApiConfig(context); break; case "WechartInterface": WechartInterface(context); break; default: context.Response.Write("无效参数"); break; } context.Response.End(); } //接入微信 public void GetWxJsApiConfig(HttpContext context) { JSSDk_Helper.GetWxJsApiConfig(context); } public void WechartInterface(HttpContext context) { JSSDk_Helper.WechartInterface(context); } public bool IsReusable { get { return false; } } } //JSSDk_Helper public static class JSSDk_Helper { public static string AppID="", AppSecret=""; public static string token=""; public static void GetWxJsApiConfig(HttpContext context){ string jsapi_ticket = GetJsApiTicket(context); // 假设这是你从某处获取的jsapi_ticket string noncestr = CreateNonceStr(); // 生成随机字符串 int timestamp = GetTimestamp(); // 获取时间戳 string url = context.Request.QueryString["url"]; // 假设URL作为查询参数传递 // 排序 string[] arr = new string[] { "jsapi_ticket=" + jsapi_ticket, "noncestr=" + noncestr, "timestamp=" + timestamp, "url=" + url.UrlEncode() }; Array.Sort(arr); // 拼接 string string1 = string.Join("&", arr); // sha1加密 string signature = FormsAuthentication.HashPasswordForStoringInConfigFile(string1, "SHA1").ToLower(); // 返回结果 context.Response.ContentType = "application/json"; context.Response.Write(new JavaScriptSerializer().Serialize(new { appId=AppID, noncestr = noncestr, timestamp = timestamp, signature = signature })); } // 辅助方法:生成随机字符串 private static string CreateNonceStr() { int length=32; Random rand = new Random(); const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; char[] buffer = new char[length]; for (int i = 0; i < length; i++) { buffer[i] = chars[rand.Next(chars.Length)]; } return new string(buffer); } // 辅助方法:获取时间戳 private static int GetTimestamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt32(ts.TotalSeconds); } // 注意:需要添加URL编码的方法 private static string UrlEncode(this string url) { return HttpUtility.UrlEncode(url, Encoding.UTF8); } private static string GetJsApiTicket(HttpContext context) { string accessToken = getAccessToken(context); // 如果是企业号用以下 URL 获取 ticket // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken"; string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token="+accessToken+""; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode >= HttpStatusCode.OK && response.StatusCode <= HttpStatusCode.Ambiguous) { StreamReader reader = new StreamReader(response.GetResponseStream()); string responseText = reader.ReadToEnd(); reader.Close(); response.Close(); JavaScriptSerializer serializer = new JavaScriptSerializer(); ticket_model model = serializer.Deserialize<ticket_model>(responseText); return model.ticket; } return ""; } private static string getAccessToken(HttpContext context){ //https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+AppID+"&secret="+AppSecret+""; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode >= HttpStatusCode.OK && response.StatusCode <= HttpStatusCode.Ambiguous) { StreamReader reader = new StreamReader(response.GetResponseStream()); string responseText = reader.ReadToEnd(); reader.Close(); response.Close(); context.Response.Write(responseText); context.Response.End(); JavaScriptSerializer serializer = new JavaScriptSerializer(); access_token_model model = serializer.Deserialize<access_token_model>(responseText); return model.access_token; } return ""; } public class access_token_model{ public string access_token{get;set;} public string expires_in{get;set;} } public class ticket_model{ public string errcode{get;set;} public string errmsg{get;set;} public string ticket{get;set;} public string expires_in{get;set;} } }
相关资料:
https://www.cnblogs.com/hyx6/p/16559698.html

浙公网安备 33010602011771号