富贵资源网 Design By www.hznty.com

JS-SDK接口是什么"text-align: center">微信JS-SDK分享功能的.Net实现代码

关键代码分析

为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,所以.net里引用了比较高版本(.Net 4.5+)的网络包进行http请求。

private string httpGet(string url)
{
  if (url.StartsWith("https"))
    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

  HttpClient httpClient = new HttpClient();
  httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  HttpResponseMessage response = httpClient.GetAsync(url).Result;

  if (response.IsSuccessStatusCode)
  {
    string result = response.Content.ReadAsStringAsync().Result;
    return result;
  }
  return null;
}

获取access_token,先从本地的access_token.aspx里找,如果没有或者过期(7000秒),则重新到微信服务器获取。

private string getAccessToken()
{
  string accessToken = string.Empty;
  var data = JObject.Parse(getAspxFile("access_token.aspx", ASPX_HEAD[1]));
  if (data != null && long.Parse(data["expire_time"].ToString()) < Utils.ConvertTimeStamp(DateTime.Now))
  {
    string url = "https://api.weixin.qq.com/cgi-bin/token"
      + this.appId + "&secret=" + this.appSecret;
    var jRes = JObject.Parse(httpGet(url));
    accessToken = jRes["access_token"].ToString();
    if (!string.IsNullOrEmpty(accessToken))
    {
      data["expire_time"] = Utils.ConvertTimeStamp(new DateTime()) + 7000;
      data["access_token"] = accessToken;
      setAspxFile("access_token.aspx", data.ToString(), ASPX_HEAD[1]);
    }
  }
  else
    accessToken = data["access_token"].ToString();
  return accessToken;
}

获取jsapi_ticket,原理与access_token一样。

private string getJsApiTicket()
{
  string ticket = string.Empty;
  var data = JObject.Parse(getAspxFile("jsapi_ticket.aspx", ASPX_HEAD[0]));
  if (data != null && long.Parse(data["expire_time"].ToString()) < Utils.ConvertTimeStamp(DateTime.Now))
  {
    string accessToken = getAccessToken();
    string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket"
      + accessToken;
    var jRes = JObject.Parse(httpGet(url));
    ticket = jRes["ticket"].ToString();
    if (!string.IsNullOrEmpty(ticket))
    {
      data["expire_time"] = Utils.ConvertTimeStamp(new DateTime()) + 7000;
      data["jsapi_ticket"] = ticket;
      setAspxFile("jsapi_ticket.aspx", data.ToString(), ASPX_HEAD[0]);
    }
  }
  else
    ticket = data["jsapi_ticket"].ToString();
  return ticket;
}

完整代码

https://github.com/stozen/jssdk-wxshare

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com