Simple encapsulation of js sdk development and jssdk Encapsulation
Recently, I am developing a small webapp project, involving sharing (sharing with friends or sending to friends)
Function development was basically completed before New Year's Day, and APIs such as sharing were not opened at that time
So I used some methods I found on the Internet to implement it, but I cannot use it normally around New Year's Day.
A few days ago officially launched the js sdk and documentation instructions, address: http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
The main steps are as follows:
1. Get access_token through appid and appsecret;
2. Get jsapi_ticket through access_token;
3. Implement the signature algorithm;
4. initialize the wx. config parameter information;
5. Call related APIs in wx. ready
Although it is a little more difficult to call than before, but it is more secure and stable, so I immediately made adjustments to the previous Code, share the following:
[Some Code is based on the project's base class, such as cache and log. It is relatively simple and can be implemented by yourself]
The following is the background code:
/** Nextuntil * simple encapsulation of js sdk calls */using System; using System. collections. generic; using System. IO; using System. net; using System. security. cryptography; using System. text; using System. web; using KK. utility; using KK. utility. extensions; namespace M {public static class WeixinHelper {# simple encapsulation of region Get requests // <summary> initiate a GET request </summary> // <param name = "url"> request URL </param> /// <param name = "errmsg"> error message </Param> /// <param name = "parameters"> request parameter </param> /// <returns> </returns> public static string Get (string url, out string errmsg, Dictionary <string, object> parameters) {errmsg = null; var strUrl = new StringBuilder (url); if (parameters! = Null & parameters. Count> 0) {// concatenate the strUrl. Append ("? "); Foreach (KeyValuePair <string, object> keyValuePair in parameters) {strUrl. appendFormat ("{0 }={ 1} &", HttpUtility. urlEncode (keyValuePair. key, Encoding. UTF8), HttpUtility. urlEncode (keyValuePair. value. toString (), Encoding. UTF8);} strUrl. remove (strUrl. length-1, 1); // remove the "&"} var request = (HttpWebRequest) WebRequest from the last bit. create (strUrl. toString (); request. method = "GET"; request. timeout = 10000; Try {var response = (HttpWebResponse) request. GetResponse (); using (Stream stream = response. GetResponseStream () {if (stream! = Null) {var reader = new StreamReader (stream); return reader. readToEnd () ;}} catch (Exception ex) {errmsg = "request Exception:" + ex. message;} return null ;} # endregion # region SHA1 encryption algorithm /// <summary> /// SHA1 encryption algorithm /// </summary> /// <param name = "str"> string </param> /// <returns> </returns> public static string GetSha1Str (string str) {byte [] strRes = Encoding. UTF8.GetBytes (str); HashAlgorithm iSha = new SHA1CryptoServiceProvider (); strRes = iSha. computeHash (strRes); var enText = new StringBuilder (); foreach (byte iByte in strRes) {enText. appendFormat ("{0: x2}", iByte);} return enText. toString () ;}# endregion /// <summary> /// obtain the access_token required to call the js sdk. // URL: http://mp.weixin.qq.com/wiki/15/54ce45d8d30b6bf6758f68d2e95bc627.html /// </Summary> /// <returns> </returns> public static string GetAccessToken () {// The access_token can be obtained within two hours, because there is a limit on the number of times obtained within one day (2000 times), the return KK is cached for 2 hours. cache. myCache. instance. get <string> ("wxapi/jssdk/accesstoken", () =>{ string errmsg; string apiUrl = string. format (" https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= {0} & secret = {1} ", Utils. getAppId (), Utils. getAppSecret (); string responseStr = Get (apiUrl, out errmsg, null); if (responseStr = null) {KK. core. log. traceLogger. info ("failed to get access_token, response content is blank", null);} else {var dic = responseStr. JSONDeserialize <Dictionary <string, object> (); if (dic. containsKey ("access_token") {return dic ["access_token"];} else {KK. core. log. traceLogger. info ("failed to get access_token, response content:" + responseStr, null) ;}} return null ;}, 120 );} /// <summary> /// obtain the ticket required to call the js sdk // document address: http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E9.99.84.E5.BD.951-JS-SDK.E4.BD.BF.E7.94.A8.E6.9D.83.E9.99.90.E7.AD.BE.E5.90.8D.E7.AE.97.E6.B3.95 /// </Summary> /// <returns> </returns> public static string GetJsApiTicket () {// The obtained ticket is valid within two hours, because there is a limit on the number of times obtained within one day (2000 times), the return KK is cached for 2 hours. cache. myCache. instance. get <string> ("wxapi/jssdk/jsapiticket", () =>{ string errmsg; string apiUrl = string. format (" https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token= {0} & type = jsapi ", GetAccessToken (); string responseStr = Get (apiUrl, out errmsg, null); if (responseStr = null) {KK. core. log. traceLogger. info ("failed to get ticket", null);} else {var dic = responseStr. JSONDeserialize <Dictionary <string, object> (); if (dic. containsKey ("ticket") {return dic ["ticket"] ;}} return null ;}, 120 );} /// <summary> // js sdk uses The permission signature algorithm /// </summary> /// <param name = "jsapiTicket"> The jsapi_ticket. </param> /// <param name = "url"> The URL. </param> // <returns> </returns> public static Dictionary <string, string> Sign (string jsapiTicket, string url) {string nonceStr = Guid. newGuid (). toString (). replace ("-", ""); string timestamp = ConvertHelper. dateToUnix (DateTime. now, 2 ). toString (); string str = string. format ("jsapi_ticket = {0} & noncestr = {1} & timestamp = {2} & url = {3}", jsapiTicket, nonceStr, timestamp, url ); string signature = GetSha1Str (str); // return new Dictionary encrypted by SHA1 <string, string >{{ "url", url },{ "jsapi_ticket", jsapiTicket }, {"noncestr", nonceStr },{ "timestamp", timestamp },{ "signature", signature }};}}}
Webpage code [my project is webform]:
<Script src =" http://res.wx.qq.com/open/js/jweixin-1.0.0.js "> </Script> <script type =" text/javascript "> <% string jsapiTicket = M. weixinHelper. getJsApiTicket (); Dictionary <string, string> dic = M. weixinHelper. sign (jsapiTicket, Request. url. absoluteUri); %> wx. config ({debug: true, appId: 'Your appid ', timestamp: <% = dic ["timestamp"] %>, nonceStr: '<% = dic ["noncestr"] %>', signature: '<% = dic ["signature"] %>', jsApiList: ['onmenusharetimeline ', 'onmenushareappmessage', 'onmenushareqq', 'onmenushareweibo ']}); wx. ready (function () {wx. onMenuShareTimeline ({title: 'share title', link: 'link address', imgUrl: 'image address', success: function () {// callback function executed after the user confirms the sharing}, cancel: function () {// callback function executed after the user cancels the sharing}) ;}); </script>
Some minor problems were encountered during program debugging. I wonder if you have any solutions:
1. In the custom content sent to a friend, whether the description information can be wrapped (generally abstract, not considered. If it is a business card, you can display it in a branch, <br> and \ r \ n, both of which are invalid );
2. The shared URL cannot be a URL that has been rewritten. (when debugging is enabled, the system prompts that the signature is invalid. After debugging, the system finds that the URL is faulty)