C# 实现微信自定义分享的示例代码

  public static string GetMD5(string encypStr, string charset)

  {

  string retStr;

  MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

  //创建md5对象

  byte[] inputBye;

  byte[] outputBye;

  //使用GB2312编码方式把字符串转化为字节数组.

  try

  {

  inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);

  }

  catch (Exception ex)

  {

  inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);

  }

  outputBye = m5.ComputeHash(inputBye);

  retStr = System.BitConverter.ToString(outputBye);

  retStr = retStr.Replace("-", "").ToUpper();

  return retStr;

  }

  ///

  /// 随机串

  ///

  public string getNoncestr()

  {

  Random random = new Random();

  return GetMD5(random.Next(1000).ToString(), "GBK").ToLower().Replace("s", "S");

  }

  ///

  /// 时间截,自1970年以来的秒数

  ///

  public string getTimestamp()

  {

  TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);

  return Convert.ToInt64(ts.TotalSeconds).ToString();

  }

  ///

  /// 签名加密,使用SHA加密所得

  ///

  /// 签名加密参数

  /// 编码UTF-8

  ///

  public string Sha1(string content, Encoding encode)

  {

  try

  {

  SHA1 sha1 = new SHA1CryptoServiceProvider();

  byte[] bytesIn = encode.GetBytes(content);

  byte[] bytesOut = sha1.ComputeHash(bytesIn);

  sha1.Dispose();

  string result = BitConverter.ToString(bytesOut);

  result = result.Replace("-", "");

  return result;

  }

  catch (Exception ex)

  {

  throw new Exception("SHA1加密出错:" + ex.Message);

  }

  }

  ///

  /// 获取签名

  ///

  /// 微信公众号调用微信JS临时票据

  /// 随机串

  /// 时间戳

  /// 当前网页URL

  ///

  public string GetSignature(string jsapi_ticket, string nonceStr, long timestamp, string url)

  {

  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);

  return Sha1(string1Builder.ToString(), Encoding.UTF8);

  }