調(diào)用微信接口前需要準(zhǔn)備的內(nèi)容。
1.微信公眾平臺的appid
2.微信公眾平臺的secret
3..獲取tokenid
4.獲取ticket
5.生成簽名的隨機串
6.生成簽名的時間戳
7.生成簽名
具體內(nèi)容:
1.微信公眾平臺的appid
2.微信公眾平臺的secret
這兩者需要登錄到申請的微信公眾平臺中去獲取,建議寫在配置文件中
3.獲取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);      //向上面的地址發(fā)起httpget請求      //這里是封裝的一個http請求的類      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;    }這里是獲取微信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; }    }注意:在每個微信公眾號中獲取tokenid的次數(shù)是有限的,所以應(yīng)該將獲取到的tokenid儲存起來,以便后續(xù)使用。我使用的方法是將tokenid存儲在數(shù)據(jù)庫中,所以在每次使用之前都要做判斷處理
/*tokenid保存方式說明:
*可在數(shù)據(jù)庫中創(chuàng)建表:SysConfig(用戶存儲項目中的配置數(shù)據(jù))
* 字段:
* ConfigKey:用于查詢該條數(shù)據(jù)的key,做為主鍵
* ConfigValue:存儲數(shù)據(jù)的值
* TypeName:該條配置數(shù)據(jù)的名稱
* Description:說明
* CreateTime:創(chuàng)建時間
* LastModifyTime:上次修改的時間
* AllowEdit:是否可編輯
* LastValue:上一次的值
* tokenid的有效時間是兩個小時=7200秒,每重新獲取一次就更新一次LastModifyTime的值,將LastModifyTime和當(dāng)前時間進行比對,如果小于7200秒則可以不用再次獲取,反之則需要再次從微信獲取。
*/
===================================================================================================
4.獲取ticket。需要上一步中獲取到的tokenid。
/// <summary> /// 獲取ticket /// </summary> /// <param name="token">獲取到的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; }5.生成簽名的隨機串
//生成簽名的隨機串string noncestr = Guid.NewGuid().ToString().Replace("-", "");6.生成簽名的時間戳
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);string timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
7.生成簽名
string signature = MakeSha1Sign(string.Format("jsapi_ticket={0}&noncestr={1}×tamp={2}&url={3}", jsapi_ticket, noncestr, timestamp, url));/// <summary>    /// SDK生成簽名    /// 注意:需要引用System.Security.dll    /// </summary>    /// <param name="str"></param>    /// <returns>str簽名</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();    }最后可以將這些步驟封裝在一個方法中
/// <summary>    /// 獲取調(diào)用微信接口用的SDKConfig    /// </summary>    /// <param name="url"></param>    /// <returns>SDKConfig整個對象</returns>    public static JsApiConfig GetJsSdkConfig(string url)    {      //獲取tokenid      string access_token = GetWxTokenId();      //獲取ticket      string jsapi_ticket = GetTicket(access_token);      //生成簽名的隨機串      string noncestr = Guid.NewGuid().ToString().Replace("-", "");      //生成簽名的時間戳      TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);      string timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();      //簽名      string signature = MakeSha1Sign(string.Format("jsapi_ticket={0}&noncestr={1}×tamp={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,        //需要使用的JS接口列表        jsApiList = new string[] { "chooseImage", "previewImage", "uploadImage", "downloadImage" }      };      return config;    }頁面上面調(diào)用我們上面配置好的內(nèi)容
$.post('/WapCardInfo/GetSDKConfig', { url: location.href.split('#')[0] }, function (data) {  var configObj = data;      wx.config({        debug: false, // 開啟調(diào)試模式,調(diào)用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會通過log打出,僅在pc端時才會打印。        appId: configObj.appId, // 必填,公眾號的唯一標(biāo)識        timestamp: configObj.timestamp, // 必填,生成簽名的時間戳        nonceStr: configObj.nonceStr, // 必填,生成簽名的隨機串        signature: configObj.signature, // 必填,簽名,見附錄1        jsApiList: [                'checkJsApi',                'onMenuShareTimeline',                'onMenuShareAppMessage',                'onMenuShareQQ',                'onMenuShareWeibo',                'onMenuShareQZone'        ] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2      });});請求的后臺代碼
[HttpPost]    public JsonResult GetSDKConfig(string url)    {      try      {  //這里就是調(diào)用上面封裝的方法        JsSdkApi.jsapiConfig model = JsSdkApi.GetJsSdkConfig(url);        return Json(model);      }      catch (Exception ex)      {        LogHelper.Error("獲取wxconfig出現(xiàn)異常:" + ex.Message.Replace("'", "/""));        return Json(new JsSdkApi.jsapiConfig());      }    }至于需要的接口就去微信公眾平臺開發(fā)者文檔中去查看啦。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答
圖片精選