目录
需求与调整
代码实现
获取令牌
生成合法票据
获取有效签名
客户端准备
客户端实现
小结
需求与调整
在微信中打开网页应用后,可以选择将地址发送给朋友进行分享,如下图:
在实际的应用中,我们可能不是简单的将该网页的链接直接分享出去,而是生成符合实际需要的URL,微信称其为自定义分享。意思即,在用户点击“转发给朋友”按钮之前,进行URL等内容的更新 ,经过调整后,再把链接发送给要分享的朋友。微信给出的关键方法是:updateAppMessageShareData。
需要注意的是:
最好不要再使用 wx.onMenuShareTimeline、wx.onMenuShareAppMessage、wx.onMenuShareQQ、wx.onMenuShareQZone 接口,请尽快迁移使用客户端6.7.2及JSSDK 1.4.0以上版本而支持 wx.updateAppMessageShareData、wx.updateTimelineShareData接口。
代码实现
获取令牌
获取令牌是调用API的基础,请提供合法的APPID和APPSECRET,示例代码如下:
public string GetAccessToken() { string accessToken = ""; //获取配置信息Datatable string respText = ""; //获取appid和appsercret string wechat_appid = ""; string wechat_appsecret = ""; //获取josn数据 string getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}"; string url = string.Format(getAccessTokenUrl, wechat_appid, wechat_appsecret); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream resStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(resStream, Encoding.Default); respText = reader.ReadToEnd(); resStream.Close(); } JavaScriptSerializer Jss = new JavaScriptSerializer(); Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText); //通过键access_token获取值 try { accessToken = respDic["access_token"].ToString(); } catch (Exception e) { accessToken =e.Message; } return accessToken; }
生成合法票据
正式调用前需要生成合法的票据,C#示例代码如下:
public string getJsapi_ticket(string accessToken) { string content = ""; try { string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi"; string method = "GET"; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = method; request.ContentType = "text/html"; request.Headers.Add("charset", "utf-8"); //发送请求并获取响应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); StreamReader sr = new StreamReader(responseStream, Encoding.UTF8); //获取返回过来的结果 content = sr.ReadToEnd(); dynamic resultStr = JsonConvert.DeserializeObject(content, new { errcode = "", errmsg = "", ticket = "", expires_in = "" }.GetType()); //请求成功 if (resultStr.errcode == "0" && resultStr.errmsg == "ok") { content = resultStr.ticket; } else { content = ""; } return content; } catch (Exception ex) { content = ex.Message; return content; } }
获取有效签名
通过获取成功的票据信息,生成有效签名后,就可以在客户端进行调用及分享了,示例代码如下:
public static string GetMD5(string encypStr, string charset) { string retStr; MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider(); //创建md5对象 byte[] inputBye; byte[] outputBye; //使用GB2312编码方式把字符串转化为字节数组. try { inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr); } catch (Exception ex) { inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr); } outputBye = m5.ComputeHash(inputBye); retStr = System.BitConverter.ToString(outputBye); retStr = retStr.Replace("-", "").ToUpper(); return retStr; } /// <summary> /// 随机串 /// </summary> public string getNoncestr() { Random random = new Random(); return GetMD5(random.Next(1000).ToString(), "GBK").ToLower().Replace("s", "S"); } /// <summary> /// 时间截,自1970年以来的秒数 /// </summary> public string getTimestamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } /// <summary> /// 签名加密,使用SHA加密所得 /// </summary> /// <param name="content">签名加密参数</param> /// <param name="encode">编码UTF-8</param> /// <returns></returns> public string Sha1(string content, Encoding encode) { try { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] bytesIn = encode.GetBytes(content); byte[] bytesOut = sha1.ComputeHash(bytesIn); sha1.Dispose(); string result = BitConverter.ToString(bytesOut); result = result.Replace("-", ""); return result; } catch (Exception ex) { throw new Exception("SHA1加密出错:" + ex.Message); } } /// <summary> /// 获取签名 /// </summary> /// <param name="jsapi_ticket">