ylbtech-微信公众平台:扫一扫demo |
1.返回顶部 |
1、Web.config
<appSettings> <add key="appid" value="<appid>"/> <add key="secret" value="<secret>"/> </appSettings>
2、
2.返回顶部 |
1、GetWxConfig.aspx.cs
using System; using System.Configuration; using System.Net; using System.Text; using System.Web.Security; using System.Web.Services; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Gyg.Web.wechat { public partial class GetWxConfig : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } #region 获取AccessToken /// <summary> /// 获取AccessToken /// </summary> /// <returns></returns> 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 /// <summary> /// 获取Jsapi_Ticket /// </summary> /// <param name="accessToken"></param> /// <returns></returns> 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 基础字符 /// <summary> /// 基础字符 /// </summary> 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 创建随机字符串 /// <summary> /// 创建随机字符串 /// </summary> /// <returns></returns> 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 创建时间戳 /// <summary> /// 创建时间戳 /// </summary> /// <returns></returns> 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 { //WxLog.Debug("进入方法", "来了"); //生成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; } } } }
2、
3.返回顶部 |
1、demo.html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>微信JS-SDK Demo</title> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"> <link rel="stylesheet" href="./src/style.css"> <script src="../jQuery.js"></script> </head> <body ontouchstart=""> <div class="lbox_close wxapi_form"> <h3 id="menu-scan">微信扫一扫</h3> <span class="desc">调起微信扫一扫接口</span> <button class="btn btn_primary" id="scanQRCode0">scanQRCode(微信处理结果)</button> <button class="btn btn_primary" id="scanQRCode1">scanQRCode(直接返回结果)</button> </div> <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <script> /* * 注意: * 1. 所有的JS接口只能在公众号绑定的域名下调用,公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。 * 2. 如果发现在 Android 不能分享自定义内容,请到官网下载最新的包覆盖安装,Android 自定义分享接口需升级至 6.0.2.58 版本及以上。 * 3. 常见问题及完整 JS-SDK 文档地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html * * 开发中遇到问题详见文档“附录5-常见错误及解决办法”解决,如仍未能解决可通过以下渠道反馈: * 邮箱地址:weixin-open@qq.com * 邮件主题:【微信JS-SDK反馈】具体问题 * 邮件内容说明:用简明的语言描述问题所在,并交代清楚遇到该问题的场景,可附上截屏图片,微信团队会尽快处理你的反馈。 */ var link = location.href; $.ajax({ url: "/wechat/GetWxConfig.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, appId: datad.appid, timestamp: datad.timestamp, nonceStr: datad.noncestr, signature: datad.signature, jsApiList: [ 'scanQRCode' ] }); wx.error(function (res) { alert(res); }); }, error: function (e) { alert(e.responseText); } }); </script> <script src="./src/demo.js"> </script> </body> </html>
2、src/demo.js
/* * 注意: * 1. 所有的JS接口只能在公众号绑定的域名下调用,公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。 * 2. 如果发现在 Android 不能分享自定义内容,请到官网下载最新的包覆盖安装,Android 自定义分享接口需升级至 6.0.2.58 版本及以上。 * 3. 完整 JS-SDK 文档地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html * * 如有问题请通过以下渠道反馈: * 邮箱地址:weixin-open@qq.com * 邮件主题:【微信JS-SDK反馈】具体问题 * 邮件内容说明:用简明的语言描述问题所在,并交代清楚遇到该问题的场景,可附上截屏图片,微信团队会尽快处理你的反馈。 */ wx.ready(function () { // 9 微信原生接口 // 9.1.1 扫描二维码并返回结果 document.querySelector('#scanQRCode0').onclick = function () { wx.scanQRCode(); }; // 9.1.2 扫描二维码并返回结果 document.querySelector('#scanQRCode1').onclick = function () { wx.scanQRCode({ needResult: 1, desc: 'scanQRCode desc', success: function (res) { alert(JSON.stringify(res)); } }); }; }); wx.error(function (res) { alert(res.errMsg); });
3、
4.返回顶部 |
5.返回顶部 |
6.返回顶部 |
![]() | 作者:ylbtech 出处:http://ylbtech.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 |