1.先看前端代码。
网上查了很多资料,前端代码是这样的
(1)需要引用官方的js文件:
(2)相信查过其它资料的大兄弟们都能看的懂,这里唯一要点是微信签名怎么生成
2.接下去我们来看微信签名怎么生成
(1)先取到“access_token” ,注意这里的access_token和“https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code” 授权后用code获取的access_token是不一样的,这里需要用“https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}”这个接口获取。
BaseAccessTokenDTO BaseAccessTokenDTO = this.Post(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appID, appsecret));
(2)接着通过access_token获取“ticket”
ticketDTO ticketDTO = this.Post(string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", BaseAccessTokenDTO.access_token));
JSApiTicket = CreateSignature(appID, ticketDTO.ticket, Request.Url.AbsoluteUri);
“JSApiTicket”是一个json变量,会赋值给前台,“CreateSignature(appID, ticketDTO.ticket, Request.Url.AbsoluteUri)” 是一个拼接签名的方法
///
/// 生成微信签名
///
///
public string CreateSignature(string APPID, string Ticket, string url)
{
var ticket = Ticket;
string noncestr = CreatenNonce_str();
long timestamp = CreatenTimestamp();
var string1Builder = new StringBuilder();
string1Builder.Append("jsapi_ticket=").Append(ticket).Append("&")
.Append("noncestr=").Append(noncestr).Append("&")
.Append("timestamp=").Append(timestamp).Append("&")
.Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
string string1 = string1Builder.ToString();
//建立SHA1对象
SHA1 sha = new SHA1CryptoServiceProvider();
//将mystr转换成byte[]
ASCIIEncoding enc = new ASCIIEncoding();
byte[] dataToHash = enc.GetBytes(string1);
//Hash运算
byte[] dataHashed = sha.ComputeHash(dataToHash);
//将运算结果转换成string
string hash = BitConverter.ToString(dataHashed).Replace("-", "");
FileWrite.WriteTextLog("签名jsapi_ticket:" + ticket);
FileWrite.WriteTextLog("签名signature:" + string1);
return "{\"appId\":\"" + APPID + "\",\"timestamp\":\"" + timestamp + "\",\"nonceStr\":\"" + noncestr + "\",\"signature\":\"" + hash + "\"}";
}
private static string[] strs = new string[]
{
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
};
///
/// 创建随机字符串
///本代码来自开源微信SDK项目:https://github.com/night-king/weixinSDK
///
///
public string CreatenNonce_str()
{
Random r = new Random();
var sb = new StringBuilder();
var length = strs.Length;
for (int i = 0; i < 15; i++)
{
sb.Append(strs[r.Next(length - 1)]);
}
return sb.ToString();
}
///
/// 创建时间戳
///本代码来自开源微信SDK项目:https://github.com/night-king/weixinSDK
///
///
public long CreatenTimestamp()
{
return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}
开发过程中遇到的问题:“config:invalid url donmain” 。 wx.config中报错
开始以为是签名生成的不对,后来发现还需要在公众号平台上面配置“JS接口域名”
下图