WeChat JS-SDK using permission signature algorithm server implementation (. net version), js-sdk.net

Source: Internet
Author: User
Tags sha1 encryption

The JS-SDK uses the server-side Implementation of the permission signature algorithm (. net version), js-sdk.net

I. Summary

This open JS interface opens a large number of api permissions, even in the unauthenticated subscription number can also use the image interface, audio interface, intelligent interface, geographical location, interface operations, scan and other functions. You must know that the previous subscription number can only accept and passively reply to user messages.The. net version is not officially provided,There are java, node, php, and python, but there is no. net version,What's wrong with this? This article teaches you how to implement the. net versionJS-SDK permission Signature generation algorithm.


This will greatly stimulate the enthusiasm of js front-end developers and allow them to do more things, so they do not have to survive in the same way as weixinbridge.
I think this should have been done for a long time in a world where js is rampant. It was because there was no js interface and users could not be shared in the middle, resulting in poor user experience. Now this problem has been solved.

However, it is the only defect that the sharing interface is not fully developed. It is a little inconvenient for Unauthenticated subscription numbers.
However, the original statement function has recently been enabled. For Unauthenticated public accounts, if the sharing interface is enabled, the original statement cannot be protected.
If you want to share the information, authenticate it.

Prevent leeching. Original address: www.cnblogs.com/deepleo/p/weixinjssdk.html

Ii. Business Logic

The public account must be generated before calling the JS interface.The JS-SDK uses the permission signature, this part of the logic needs the user to implement in the server, relatively unreliable is the official does not give the. net version of the demo.

There are java, node, php, and python, but there is no. net version. You are not mistaken.

Well, we can achieve it ourselves.

 

The generation method is as follows (from the official document)

Appendix 1-JS-SDK permission Signature Algorithm

Jsapi_ticket

Before generating a signature, you must first understand jsapi_ticket. jsapi_ticket is a temporary ticket used by the public account to call the JS interface. Under normal circumstances, jsapi_ticket is valid for 7200 seconds and obtained through access_token. Because jsapi_ticket has a limited number of api calls, refreshing jsapi_ticket frequently limits api calls and affects your business. Developers must cache jsapi_ticket globally in their own services.

The following JSON is returned:

{"errcode":0,"errmsg":"ok","ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA","expires_in":7200}

After obtaining jsapi_ticket, you can generate a signature for JS-SDK permission verification.

 

Signature Algorithm

The signature generation rules are as follows: the fields involved in the signature include noncestr (random string), valid jsapi_ticket, timestamp (timestamp), url (URL of the current webpage, does not contain # And the following parts ). After all parameters to be signed are sorted in ascending order (lexicographically) according to the field name ASCII code, the format of the URL key-value pair is used (that is, key1 = value1 & key2 = value2 ...) Concatenate the string into string1. Note that all parameter names are lowercase characters. Perform sha1 encryption on string1, and use original values for field names and field values without URL escaping.


Signature = sha1 (string1 ). Example:

  • Noncestr = Wm3WZYTPz0wzccnW
  • Jsapi_ticket = sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg
  • Time stamp = 1414587457
  • Url = http://mp.weixin.qq.com? Params = value


Step 1. Sort all parameters to be signed in ascending order of the ASCII code of Field Names (lexicographically), and then use the format of the URL key-Value Pair (that is, key1 = value1 & key2 = value2 ...) Concatenate the string into string1:

jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value


Step 2. Sign string1 sha1 to obtain signature:

0f9de62fce790f9a083d5c99e95740ceb90c27ed

Notes

Iii. Code Implementation

1. GetJsapi_ticket

/// <Summary> /// obtain jsapi_ticket // jsapi_ticket is a temporary ticket used by the public account to call the JS interface. /// Normally, jsapi_ticket is valid for 7200 seconds and is obtained through access_token. /// Due to the limited number of api calls to obtain jsapi_ticket, frequent refreshing of jsapi_ticket results in limited api calls and affects your own business. Developers must cache jsapi_ticket globally in their own services.
/// The Code comes from the open source SDK project: https://github.com/night-king/weixinSDK /// </summary> /// <param name = "access_token"> access_token obtained by BasicAPI, you can also use TokenHelper to obtain </param> /// <returns> </returns> public static dynamic GetTickect (string access_token) {var url = string. format ("https://api.weixin.qq.com/cgi-bin/ticket/getticket? Access_token = {0} & type = jsapi ", access_token); var client = new HttpClient (); var result = client. GetAsync (url). Result; if (! Result. IsSuccessStatusCode) return string. Empty; var jsTicket = DynamicJson. Parse (result. Content. ReadAsStringAsync (). Result); return jsTicket ;}

 

2.Signature Algorithm

Before signing, we need to solve the problem of random strings and timestamps,

2.1Random string Generation Algorithm

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", "", "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"}; // <summary> // create a random string
/// The Code comes from the open source SDK project: https://github.com/night-king/weixinSDK /// </summary> /// <returns> </returns> public 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 ();}

2.2Timestamp

The timestamp references this: http://tool.chinaz.com/Tools/unixtime.aspx

/// <Summary> /// creation Timestamp
/// The Code comes from the open source SDK project: https://github.com/night-king/weixinSDK /// </summary> /// <returns> </returns> public static long CreatenTimestamp () {return (DateTime. now. toUniversalTime (). ticks-621355968000000000)/10000000 ;}

2.3 The signature algorithm is as follows:

/// <Summary> // Signature Algorithm
/// This code is from the open-source SDK project: https://github.com/night-king/weixinSDK /// </Summary> /// <param name = "jsapi_ticket"> jsapi_ticket </param> /// <param name = "noncestr"> random string (must be consistent with wx. nonceStr in config) </param> // <param name = "timestamp"> timestamp (must be the same as wx. the timestamp in config is the same) </param> // <param name = "url"> the URL of the current webpage, does not contain # And the following parts (the complete URL of the JS interface page must be called) </param> // <returns> </returns> public static string GetSignature (string jsapi_ticket, string noncestr, long timestamp, string url, out str Ing 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 Util. Sha1 (string1 );}

 

To get all the code, click: https://github.com/night-king/weixinSDK/blob/master/Deepleo.Weixin.SDK/JSSDK/JSAPI.cs

 

Online Demo: http://weixinsdk.deepleo.com/jssdk
You can also scan the QR code to view it in:

(This code from open source SDK project: https://github.com/night-king/weixinSDK)

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.