步骤一:绑定域名
在JS接口安全域名中输入绑定的域名。可以绑定3个
步骤二:引入JS文件
在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.0.0.js
如需使用摇一摇周边功能,请引入 http://res.wx.qq.com/open/js/jweixin-1.1.0.js
备注:支持使用 AMD/CMD 标准模块加载方法加载
在我的网页中,只需要加入<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>这行即可。
步骤三:通过config接口注入权限验证配置
所有需要使用JS-SDK的页面必须先注入配置信息,否则将无法调用(同一个url仅需调用一次,对于变化url的SPA的web app可在每次url变化时进行调用,目前Android微信客户端不支持pushState的H5新特性,所以使用pushState来实现web app的页面会导致签名失败,此问题会在Android6.2中修复)。
<script>//页面上js
wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '自己的APPID', // 必填,公众号的唯一标识
timestamp: <%=timestamp%> , // 必填,生成签名的时间戳
nonceStr: '<%=nonceStr%>',// 必填,生成签名的随机串
signature: '<%=signature %>',// 必填,签名,见附录1
jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage','onMenuShareQQ'] // 必填,我这里只填了3,需要使用的JS接口列表,所有JS接口列表见附录2
});
</script>
学习timestamp,nonceStr,nonceStr三个参数如何实现
namespace 命名空间
{
public partial class report : System.Web.UI.Page
{
public string timestamp, nonceStr, signature;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
timestamp = getTimestamp();
nonceStr = getNoncestr();
signature = Getsignature(nonceStr, timestamp);
}
}
#region timespan生成签名的时间戳
///
/// 生成时间戳
/// 从 1970 年 1 月 1 日 00:00:00 至今的秒数,即当前的时间,且最终需要转换为字符串形式
///
///
public string getTimestamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
#endregion
#region nonceStr生成签名的随机串:
///
/// 生成随机字符串
///
///
public string getNoncestr()
{
Random random = new Random();
return MD5Util.GetMD5(random.Next(1000).ToString(), "GBK");
}
///
/// MD5Util 的摘要说明。
///
public class MD5Util
{
public MD5Util()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/** 获取大写的MD5签名结果 */
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;
}
}
#endregion
#region singature签名的生成
///
/// 获取access_token
///
///
public string Getaccesstoken()
{
string appid = "appid";
string secret = "appsecret";
string urljson = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
string strjson = "";
UTF8Encoding encoding = new UTF8Encoding();
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(urljson);
myRequest.Method = "GET";
myRequest.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse response;
Stream responseStream;
StreamReader reader;
string srcString;
response = myRequest.GetResponse() as HttpWebResponse;
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
srcString = reader.ReadToEnd();
reader.Close();
if (srcString.Contains("access_token"))
{
//CommonJsonModel model = new CommonJsonModel(srcString);
CommonJsonModel model = new CommonJsonModel(srcString);
strjson = model.GetValue("access_token");
Session["access_tokenzj"] = strjson;
}
return strjson;
}
public class CommonJsonModelAnalyzer
{
protected string _GetKey(string rawjson)
{
if (string.IsNullOrEmpty(rawjson))
return rawjson;
rawjson = rawjson.Trim();
string[] jsons = rawjson.Split(new char[] { ':' });
if (jsons.Length < 2)
return rawjson;
return jsons[0].Replace("\"", "").Trim();
}
protected string _GetValue(string rawjson)
{
if (string.IsNullOrEmpty(rawjson))
return rawjson;
rawjson = rawjson.Trim();
string[] jsons = rawjson.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
if (jsons.Length < 2)
return rawjson;
StringBuilder builder = new StringBuilder();
for (int i = 1; i < jsons.Length; i++)
{
builder.Append(jsons[i]);
builder.Append(":");
}
if (builder.Length > 0)
builder.Remove(builder.Length - 1, 1);
string value = builder.ToString();
if (value.StartsWith("\""))
value = value.Substring(1);
if (value.EndsWith("\""))
value = value.Substring(0, value.Length - 1);
return value;
}
protected List
_GetCollection(string rawjson)
{
//[{},{}]
List
list = new List
();
if (string.IsNullOrEmpty(rawjson))
return list;
rawjson = rawjson.Trim();
StringBuilder builder = new StringBuilder();
int nestlevel = -1;
int mnestlevel = -1;
for (int i = 0; i < rawjson.Length; i++)
{
if (i == 0)
continue;
else if (i == rawjson.Length - 1)
continue;
char jsonchar = rawjson[i];
if (jsonchar == '{')
{
nestlevel++;
}
if (jsonchar == '}')
{
nestlevel--;
}
if (jsonchar == '[')
{
mnestlevel++;
}
if (jsonchar == ']')
{
mnestlevel--;
}
if (jsonchar == ',' && nestlevel == -1 && mnestlevel == -1)
{
list.Add(builder.ToString());
builder = new StringBuilder();
}
else
{
builder.Append(jsonchar);
}
}
if (builder.Length > 0)
list.Add(builder.ToString());
return list;
}
}
public class CommonJsonModel : CommonJsonModelAnalyzer
{
private string rawjson;
private bool isValue = false;
private bool isModel = false;
private bool isCollection = false;
public CommonJsonModel(string rawjson)
{
this.rawjson = rawjson;
if (string.IsNullOrEmpty(rawjson))
throw new Exception("missing rawjson");
rawjson = rawjson.Trim();
if (rawjson.StartsWith("{"))
{
isModel = true;
}
else if (rawjson.StartsWith("["))
{
isCollection = true;
}
else
{
isValue = true;
}
}
public string Rawjson
{
get { return rawjson; }
}
public bool IsValue()
{
return isValue;
}
public bool IsValue(string key)
{
if (!isModel)
return false;
if (string.IsNullOrEmpty(key))
return false;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
return submodel.IsValue();
}
}
return false;
}
public bool IsModel()
{
return isModel;
}
public bool IsModel(string key)
{
if (!isModel)
return false;
if (string.IsNullOrEmpty(key))
return false;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
return submodel.IsModel();
}
}
return false;
}
public bool IsCollection()
{
return isCollection;
}
public bool IsCollection(string key)
{
if (!isModel)
return false;
if (string.IsNullOrEmpty(key))
return false;
foreach (string subjson in base._GetCollection(this.rawjson))
{
CommonJsonModel model = new CommonJsonModel(subjson);
if (!model.IsValue())
continue;
if (model.Key == key)
{
CommonJsonModel submodel = new CommonJsonModel(model.Value);
return submodel.IsCollection();
}
}
return false;
}
///
/// 当模型是对象,返回拥有的key
///
///
public List
GetKeys()
{
if (!isModel)
return null;
List
list = new List
(); foreach (string subjson in base._GetCollection(this.rawjson)) { string key = new CommonJsonModel(subjson).Key; if (!string.IsNullOrEmpty(key)) list.Add(key); } return list; } ///
/// 当模型是对象,key对应是值,则返回key对应的值 /// ///
///
public string GetValue(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) return model.Value; } return null; } ///
/// 模型是对象,key对应是对象,返回key对应的对象 /// ///
///
public CommonJsonModel GetModel(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); if (!submodel.IsModel()) return null; else return submodel; } } return null; } ///
/// 模型是对象,key对应是集合,返回集合 /// ///
///
public CommonJsonModel GetCollection(string key) { if (!isModel) return null; if (string.IsNullOrEmpty(key)) return null; foreach (string subjson in base._GetCollection(this.rawjson)) { CommonJsonModel model = new CommonJsonModel(subjson); if (!model.IsValue()) continue; if (model.Key == key) { CommonJsonModel submodel = new CommonJsonModel(model.Value); if (!submodel.IsCollection()) return null; else return submodel; } } return null; } ///
/// 模型是集合,返回自身 /// ///
public List
GetCollection() { List
list = new List
(); if (IsValue()) return list; foreach (string subjson in base._GetCollection(rawjson)) { list.Add(new CommonJsonModel(subjson)); } return list; } ///
/// 当模型是值对象,返回key /// private string Key { get { if (IsValue()) return base._GetKey(rawjson); return null; } } ///
/// 当模型是值对象,返回value /// private string Value { get { if (!IsValue()) return null; return base._GetValue(rawjson); } } } #endregion #region 获取jsapi_ticket public string Getjsapi_ticket() { string accesstoken = (string)Session["access_tokenzj"]; string urljson = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accesstoken + "&type=jsapi"; string strjson = ""; UTF8Encoding encoding = new UTF8Encoding(); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(urljson); myRequest.Method = "GET"; myRequest.ContentType = "application/x-www-form-urlencoded"; HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8); string srcString = reader.ReadToEnd(); reader.Close(); if (srcString.Contains("ticket")) { CommonJsonModel model = new CommonJsonModel(srcString); strjson = model.GetValue("ticket"); Session["ticketzj"] = strjson; } return strjson; } #endregion #region 生成signature public string Getsignature(string nonceStr, string timespanstr) { if (Session["access_tokenzj"] == null) { Getaccesstoken(); } if (Session["ticketzj"] == null) { Getjsapi_ticket(); } string url = Request.Url.ToString(); string str = "jsapi_ticket=" + (string)Session["ticketzj"] + "&noncestr=" + nonceStr + "×tamp=" + timespanstr + "&url=" + url;// +"&wxref=mp.weixin.qq.com"; string singature = SHA1Util.getSha1(str); string ss = singature; return ss; } #endregion } } class SHA1Util { public static String getSha1(String str) { //建立SHA1对象 SHA1 sha = new SHA1CryptoServiceProvider(); //将mystr转换成byte[] ASCIIEncoding enc = new ASCIIEncoding(); byte[] dataToHash = enc.GetBytes(str); //Hash运算 byte[] dataHashed = sha.ComputeHash(dataToHash); //将运算结果转换成string string hash = BitConverter.ToString(dataHashed).Replace("-", ""); return hash; } }
title : '文章标题',
desc : ' 描述',
link : '网页链接',
imgUrl : '图片地址',
};
wx.ready(function(){
wx.onMenuShareAppMessage(obj);
// 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
wx.onMenuShareTimeline(obj);
// 2.3 监听“分享到QQ”按钮点击、自定义分享内容及分享结果接口
//wx.onMenuShareQQ(obj);
wx.onMenuShareQQ({
title : '查询',
desc : ' 平台。',
link : 'http://kyapp.webris.cn/qzt/report.html',
imgUrl : 'http://kyapp.webris.cn/二维码.jpg',
trigger: function (res) {
alert('用户点击分享到QQ');
},
complete: function (res) {
alert(JSON.stringify(res));
},
success: function (res) {
alert('已分享');
},
cancel: function (res) {
alert('已取消');
},
fail: function (res) {
alert(JSON.stringify(res));
}
});
alert('已注册获取“分享到 QQ”状态事件');
};
</script>
当我们完成上面步骤之后,进入微信web开发者工具中进行调试,如下图,请在步骤1的安全域名下
1.
配置的3个JS接口都已注册。配置的权限验证也已正常。
当点击按钮时,触发事件
2.
在弹出的底部菜单上点击分享到QQ时
3.
4.
5.
6.
其他功能类似。以上操作就可以实现分享自定义的文章内容了