What you need to prepare before calling the WeChat interface.
1. The appid of WeChat public platform
2. WeChat public platform secret
3..Get tokenid
4. Get ticket
5. Generate a random string of signatures
6. Generate the signature timestamp
7. Generate a signature
Specific content:
1. The appid of WeChat public platform
2. WeChat public platform secret
Both of these need to be logged in to the WeChat public platform you applied for to obtain. It is recommended to write them in the configuration file
3. Get tokenid
public static string GetWxTokenId() { string token = ""; string url = ("/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret); //Stack httpget request to the above address //This is an encapsulated http request class string content = (url); if (!(content)) { var obj = <TokenResult>(content); if (!) { token = obj.access_token; } } return token; }
Here is the return object to get WeChat 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; } }
Note: The number of times you get tokenid in each WeChat official account is limited, so the obtained tokenid should be stored for subsequent use. The method I use is to store the tokenid in the database, so I have to make judgments before each use
/*Tokenid save method description:
*Create tables in the database: SysConfig (user stores configuration data in the project)
* Fields:
* ConfigKey: The key used to query the data as the primary key
* ConfigValue: The value of the data is stored
* TypeName: The name of the configuration data
* Description: Description
* CreateTime: Creation time
* LastModifyTime: Last modified time
* AllowEdit: Is it editable?
* LastValue: the last value
* The valid time of tokenid is two hours = 7200 seconds. The value of LastModifyTime is updated every time it is re-acquisitioned. Comparison of LastModifyTime with the current time. If it is less than 7200 seconds, you don’t need to get it again. Otherwise, you need to get it again from WeChat.
*/
===================================================================================================
4. Get the ticket. Need tokenid obtained in the previous step.
/// <summary> /// Get ticket /// </summary> /// <param name="token">acquired tokenid</param> /// <returns>strticket</returns> public static string GetTicket(string token) { string getticketurl = ("/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", token); string content = (getticketurl); JsApiTicket obj = <JsApiTicket>(content); return ; }
5. Generate a random string of signatures
//Generate a random string of signaturestring noncestr = ().ToString().Replace("-", "");
6. Generate the signature timestamp
TimeSpan ts = - new DateTime(1970, 1, 1, 0, 0, 0, 0); string timestamp = Convert.ToInt64().ToString();
7. Generate a signature
string signature = MakeSha1Sign(("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", jsapi_ticket, noncestr, timestamp, url)); /// <summary> /// SDK generates signature /// Note: Quotation is required /// </summary> /// <param name="str"></param> /// <returns>str signature</returns> public static string MakeSha1Sign(string str) { byte[] StrRes = (str); HashAlgorithm iSHA = new SHA1CryptoServiceProvider(); StrRes = (StrRes); StringBuilder EnText = new StringBuilder(); foreach (byte iByte in StrRes) { ("{0:x2}", iByte); } return (); }
Finally, these steps can be encapsulated in a method
/// <summary> /// Get the SDKConfig used to call the WeChat interface /// </summary> /// <param name="url"></param> /// <returns>SDKConfig entire object</returns> public static JsApiConfig GetJsSdkConfig(string url) { //Get tokenid string access_token = GetWxTokenId(); //Get ticket string jsapi_ticket = GetTicket(access_token); //Generate a random string of signature string noncestr = ().ToString().Replace("-", ""); // Generate the signature timestamp TimeSpan ts = - new DateTime(1970, 1, 1, 0, 0, 0, 0); string timestamp = Convert.ToInt64().ToString(); //sign string signature = MakeSha1Sign(("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 use jsApiList = new string[] { "chooseImage", "previewImage", "uploadImage", "downloadImage" } }; return config; }
The page calls the content we configured above
$.post('/WapCardInfo/GetSDKConfig', { url: ('#')[0] }, function (data) { var configObj = data; ({ debug: false, // Turn on debugging mode, the return values of all APIs called will be alerted on the client. To view the passed parameters, you can open them on the PC side. The parameter information will be printed through the log and will only be printed on the PC side. appId: , // Required, unique identification of the official account timestamp: , // Required to generate a signature time stamp nonceStr: , // Required to generate a random string of signatures signature: , // Required, signature, see Appendix 1 jsApiList: [ 'checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone' ] // Required, a list of JS interfaces that need to be used, and the list of all JS interfaces is shown in Appendix 2 }); });
Requested background code
[HttpPost] public JsonResult GetSDKConfig(string url) { try { //This is the method encapsulated above. model = (url); return Json(model); } catch (Exception ex) { ("Exception occurred when obtaining wxconfig:" + ("'", "\"")); return Json(new ()); } }
As for the required interface, go to the WeChat public platform developer document to view it.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.