C # code for calling the WeChat Interface,

Source: Internet
Author: User

C # code for calling an interface,

Previously, the company issued a single task for development, and then I went online to get a story. However, I feel that for new developers like me, there are too many things required, which is too messy, then the whole person is forced.

It takes a long time to complete the interface call. So, I sorted out what needs to be prepared before calling the interface.

1. appid of the public platform

2. secret of the public platform

3. Get tokenid

4. Get ticket

5. Generate a random signature string

6. Generate the signature Timestamp

7. Generate a signature

========================================================== ==========================================================

1. appid of the public platform

2. secret of the public platform

You need to log on to the requested public platform to obtain the two. We recommend that you write them in the configuration file.

========================================================== ==========================================================

3. Get tokenid

Public static string GetWxTokenId () {string token = ""; string url = string. Format ("https://api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = {0} & secret = {1} ", appid, secret ); // initiate an httpget request to the above address // here is the encapsulated http request class string content = HttpHelper. httpGet (url); if (! String. IsNullOrEmpty (content) {var obj = JsonConvert. DeserializeObject <TokenResult> (content); if (! Obj. errcode. HasValue) {token = obj. access_token;} return token ;}
Get tokenid

Here is the returned object for obtaining tokenid

private class TokenResult        {            public string access_token { get; set; }            public string expires_in { get; set; }            public int? errcode { get; set; }            public string errmsg { get; set; }        }
TokenResult

Note: The number of times the tokenid is obtained in each public number is limited. Therefore, you should store the obtained tokenid for future use. The method I use is to store the tokenid in the database, so I have to make judgments before each use.

/* Tokenid storage method description:
* You can create a table in the database: SysConfig (the user stores the configuration data in the project)
* Field:
* ConfigKey: The key used to query the data. It is used as the primary key.
* ConfigValue: the value of the stored data.
* TypeName: name of the configuration data
* Description: Description
* CreateTime: Creation Time
* LastModifyTime: The last modification time.
* AllowEdit: editable or not
* LastValue: The last value.
* The tokenid is valid for two hours = 7200 seconds. The value of LastModifyTime is updated every time it is acquired again, and the LastModifyTime is compared with the current time, if it is less than 7200 seconds, you do not need to obtain it again. Otherwise, you need to obtain it again.
*/

========================================================== ========================================================== ==============================

4. Get ticket. The tokenid that needs to be obtained in the previous step.

/// <Summary> /// obtain ticket /// </summary> /// <param name = "token"> the obtained tokenid </param> /// <returns> strticket </returns> public static string GetTicket (string token) {string getticketurl = string. format ("https://api.weixin.qq.com/cgi-bin/ticket/getticket? Access_token = {0} & type = jsapi ", token); string content = HttpHelper. httpGet (getticketurl); JsApiTicket obj = JsonConvert. deserializeObject <JsApiTicket> (content); return obj. ticket ;}
Obtain ticketid

========================================================== ========================================================== ==================================

5. Generate a random signature string

// String noncestr = Guid. NewGuid (). ToString (). Replace ("-","");
Generate a random string of the signature

========================================================== ========================================================== ================================

6. Generate the signature Timestamp

TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);string timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
Signature generation Timestamp

========================================================== ========================================================== ================================

7. Generate a signature

String signature = MakeSha1Sign (string. format ("jsapi_ticket = {0} & noncestr = {1} & timestamp = {2} & url = {3}", jsapi_ticket, noncestr, timestamp, url )); /// <summary> /// SDK generates the signature /// Note: System must be referenced. security. dll // </summary> /// <param name = "str"> </param> // <returns> str signature </returns> public static string MakeSha1Sign (string str) {byte [] StrRes = Encoding. default. getBytes (str); HashAlgorithm iSHA = new SHA1CryptoServiceProvider (); StrRes = iSHA. computeHash (StrRes); StringBuilder EnText = new StringBuilder (); foreach (byte iByte in StrRes) {EnText. appendFormat ("{0: x2}", iByte);} return EnText. toString ();}
Signature

========================================================== ========================================================== ================================

Finally, you can encapsulate these steps in a method.

/// <Summary> /// obtain the SDKConfig for calling the interface // </summary> /// <param name = "url"> </param> /// <returns> SDKConfig entire object </returns> public static JsApiConfig GetJsSdkConfig (string url) {// obtain tokenid string access_token = GetWxTokenId (); // obtain ticket string jsapi_ticket = GetTicket (access_token); // generate a random string noncestr = Guid. newGuid (). toString (). replace ("-", ""); // The timestamp TimeSpan ts = DateTime for generating the signature. utcNow-new DateTime (1970, 1, 1, 0, 0, 0, 0); string timestamp = Convert. toInt64 (ts. totalSeconds ). toString (); // signature string signature = MakeSha1Sign (string. format ("jsapi_ticket = {0} & noncestr = {1} & timestamp = {2} & url = {3}", jsapi_ticket, noncestr, timestamp, url )); jsApiConfig config = new JsApiConfig () {appId = appid, debug = false, nonceStr = noncestr, timestamp = timestamp, signature = signature, ticket = jsapi_ticket, // list of JS interfaces to be used jsApiList = new string [] {"chooseImage", "previewImage", "uploadImage", "downloadImage" }}; return config ;}
Direct call Method

========================================================== ========================================================== ==============================

The configured content is called on the page.

$. Post ('/WapCardInfo/getsdkconfig', {url: location. href. split ('#') [0]}, function (data) {var configObj = data; 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: configObj. appId, // required. timestamp is the unique identifier of the public number: configObj. timestamp, // required. The signature timestamp nonceStr: configObj. nonceStr, // required. The random signature string signature: configObj is generated. signature, // required, signature. For details, see Appendix 1 jsApiList: ['checkjsapi ', 'onmenusharetimeline', 'onmenushareappmessage', 'onmenushareqq', 'onmenushareweio ', 'onmenushareqzone '] // required. List of JS interfaces to be used. For the list of all JS interfaces, see appendix 2 });});
Page js Code

========================================================== ========================================================== ==============================

Request background code

[HttpPost] public JsonResult GetSDKConfig (string url) {try {// The above encapsulated method JsSdkApi is called here. jsapiConfig model = JsSdkApi. getJsSdkConfig (url); return Json (model);} catch (Exception ex) {LogHelper. error ("an exception occurred when obtaining wxconfig:" + ex. message. replace ("'", "\" "); return Json (new JsSdkApi. jsapiConfig ());}}
Background code

For the required interfaces, go to the public platform developer documentation to view them.

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.