WeChat development-Jssdk calls share instance,-jssdk share instance

Source: Internet
Author: User
Tags sha1 hash

Development-Jssdk calls share instance,-jssdk shares instance

Using System; using System. collections. generic; using System. linq; using System. web; using System. IO; using Newtonsoft. json; using System. net; using System. runtime. serialization. formatters. binary; using System. text; using System. security. cryptography; // <summary> /// summary of WXJSSDK /// </summary> public class WXJSSDK {private string appId; private string appSecret; private DataTable DT; public WXJSSDK (string appId, string appSecret) {this. appId = appId; this. appSecret = appSecret;} // get the data packet and return to the public System page. collections. hashtable getSignPackage () {string jsapiTicket = getJsApiTicket (); string url = HttpContext. current. request. url. toString (); string timestamp = Convert. toString (ConvertDateTimeInt (DateTime. now); string nonceStr = createNonceStr (); // here, the parameter order should be sorted in ascending order of the key value ASCII code string rawstring = "jsapi_ticket =" + jsapiTicket + "& noncestr =" + nonceStr + "& timestamp =" + timestamp + "& url =" + url + ""; string signature = SHA1_Hash (rawstring); System. collections. hashtable signPackage = new System. collections. hashtable (); signPackage. add ("appId", appId); signPackage. add ("nonceStr", nonceStr); signPackage. add ("timestamp", timestamp); signPackage. add ("url", url); signPackage. add ("signature", signature); signPackage. add ("rawString", rawstring); return signPackage;} // create a random string private string createNonceStr () {int length = 16; string chars = "character "; string str = ""; Random rad = new Random (); for (int I = 0; I <length; I ++) {str + = chars. substring (rad. next (0, chars. length-1), 1);} return str;} // obtain ticket. If the time in the file times out, obtain the private string getJsApiTicket () again () {// here I read DT = DbSession from the database. default. fromSql ("select jsapi_ticket, ticket_expires from table where ID = 1 "). toDataTable (); int expire_time = (int) DT. rows [0] ["ticket_expires"]; string ticket = DT. rows [0] ["jsapi_ticket"]. toString (); string accessToken = getAccessToken (); // obtain the global token if (expire_time <ConvertDateTimeInt (DateTime. now) {string url =" https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token= "+ AccessToken +" "; Jsapi api = JsonConvert. DeserializeObject <Jsapi> (httpGet (url); ticket = api. ticket; if (ticket! = "") {Expire_time = ConvertDateTimeInt (DateTime. now) + 7000; // database operation} return ticket;} // obtain the accesstoken. If the time in the file times out, obtain the // private string getAccessToken () again () // {// access_token should be globally stored and updated. The following code is used as an example to write data to a file: // string access_token = ""; // string path = HttpContext. current. server. mapPath (@ "/weixin/access_token.json"); // FileStream file = new FileStream (path, FileMode. open); // var serializer = new DataContractJsonSerializer (typeof (AccToken); // AccToken readJSTicket = (AccToken) serializer. readObject (file); // file. close (); // if (readJSTicket. expires_in <ConvertDateTimeInt (DateTime. now) // {// string url =" https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= "+ AppId +" & secret = "+ appSecret +" "; // AccToken iden = Desrialize <AccToken> (new AccToken (), httpGet (url )); // access_token = iden. access_token; // if (access_token! = "") // {// Iden. expires_in = ConvertDateTimeInt (DateTime. now () + 7000; // iden. access_token = access_token; // string json = Serialize <AccToken> (iden); // StreamWriterMetod (json, path ); ///} // else // {// access_token = readJSTicket. access_token; //} // return access_token; // initiate an http ball and return the private string httpGet (string url) {try {WebClient MyWebClient = new WebClient (); myWebClient. credentials = CredentialCache. defaultCredentials; // obtain or set the network credential Byte [] pageData = MyWebClient used to authenticate requests to Internet resources. downloadData (url); // download data from a specified website string pageHtml = System. text. encoding. default. getString (pageData); // If GB2312 is used to retrieve the website page, return pageHtml;} catch (WebException webEx) {Console. writeLine (webEx. message. toString (); return null ;}// SHA1 hash encryption algorithm public string SHA1_Hash (string str_sha1_in) {SHA1 sha1 = new SHA1CryptoServiceProvider (); byte [] bytes_sha1_in = System. text. UTF8Encoding. default. getBytes (str_sha1_in); byte [] bytes_sha1_out = sha1.ComputeHash (bytes_sha1_in); string str_sha1_out = BitConverter. toString (bytes_sha1_out); str_sha1_out = str_sha1_out.Replace ("-",""). toLower (); return str_sha1_out;} // <summary> // Method for writing StreamWriter to a file /// </summary> private void StreamWriterMetod (string str, string patch) {try {FileStream fsFile = new FileStream (patch, FileMode. openOrCreate); StreamWriter swWriter = new StreamWriter (fsFile); swWriter. writeLine (str); swWriter. close () ;}catch (Exception e) {throw e ;}} /// <summary> /// convert the c # DateTime time format to the Unix timestamp format /// </summary> /// <param name = "time"> time </param> // <returns> double </returns> public int ConvertDateTimeInt (System. dateTime time) {int intResult = 0; System. dateTime startTime = TimeZone. currentTimeZone. toLocalTime (new System. dateTime (1970, 1, 1); intResult = Convert. toInt32 (time-startTime ). totalSeconds); return intResult ;}// create a Json serialization and deserialization category # region // create a JSon class save file jsapi_ticket.json public class JSTicket {public string jsapi_ticket {get; set ;} public double expire_time {get; set ;}// create a JSon class to save the file access_token.json public class AccToken {public string access_token {get; set;} public double expires_in {get; set ;}}// create a class from the returned results to obtain ticket public class Jsapi {public int errcode {get; set ;}public string errmsg {get; set ;} public string ticket {get; set;} public string expires_in {get; set ;}# endregion

Then js calls:

<Script type = "text/javascript"> var dataForWeixin = {appId: "<% = appid %>", MsgImg: "<% = WeChatImg %>", TLImg: "<% = WeChatImg %>", url: "<% = url %>", title: "<% = Title %>", desc: "<% = desc %>", timestamp: '<% = timestamp %>', nonceStr: '<% = nonce %>', signature: '<% = signature %>', jsApiList: ['alipay', 'onmenushareappmessage', 'onmenushareqq', 'onmenushareweibo '], fakeid: "", callback: function () {} }; Wx. config ({debug: false, // enable the debugging mode. The returned values of all called APIs are displayed in the client alert. To view the input parameters, you can open them on the pc, the parameter information is output through log and printed only on the pc end. AppId: dataForWeixin. appId, // required. timestamp is the unique identifier of the public number: dataForWeixin. timestamp, // required. The signature timestamp nonceStr: dataForWeixin. nonceStr, // required. The random signature string signature: dataForWeixin is generated. signature, // required, signature. For details, see Appendix 1 jsApiList: dataForWeixin. jsApiList // required. List of JS interfaces to be used. For the list of all JS interfaces, see Appendix 2}. wx. ready (function () {// enter various APIs here // share them with the wx circle of friends. onMenuShareTimeline ({title: dataForWeixin. title, // share the title link: dataForWeixin. url, // share Link ImgUrl: dataForWeixin. msgImg, // share icon success: function () {// callback function executed after the user confirms the sharing}, cancel: function () {// callback function executed after the user cancels the sharing}); // share it with a friend wx. onMenuShareAppMessage ({title: dataForWeixin. title, // share the title desc: dataForWeixin. desc, // share description link: dataForWeixin. url, // share link imgUrl: dataForWeixin. TLImg, // share icon type: '', // share type, music, video, or link. If not specified, the default value is link dataUrl:''. // if the type is music or video, the data link is provided. The default value is suc. Cess: function () {// callback function executed after the user confirms the sharing}, cancel: function () {// callback function executed after the user cancels the sharing }}); // QQ wx. onMenuShareQQ ({title: dataForWeixin. title, // share the title desc: dataForWeixin. desc, // share description link: dataForWeixin. url, // share link imgUrl: dataForWeixin. msgImg, // share icon success: function () {// callback function executed after the user confirms the sharing}, cancel: function () {// callback function executed after the user cancels the sharing}); // QQ Weibo wx. onMenuShareWeibo ({title: dataForWeixin. title ,// Share title desc: dataForWeixin. desc, // share description link: dataForWeixin. url, // share link imgUrl: dataForWeixin. TLImg, // share icon success: function () {// callback function executed after the user confirms the sharing}, cancel: function () {// callback function executed after the user cancels the sharing}); // The ready method is executed after the config information is verified. All interfaces must be called after the result is obtained by the config interface, config is a client-side asynchronous operation. // if you need to call the interface when loading the page, you must place the interface in the ready function to ensure correct execution. You can directly call the interface that is called only when the user triggers the operation, and do not need to put it in the ready function. }); Wx. error (function (res) {// alert (res); // If the config information fails to be verified, the error function is executed. If the signature expires, the verification fails, for specific error information, you can view the debug mode of config or the res parameter returned. For SPA, you can update the signature here. }); </Script>

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.