一直都想研究一下JS-SDK微信分享的接口调用,由于最近工作需要,研究了一下,目前只是实现了部分接口的调用;其他接口调用也是类似的;
在开发之前,需要提前准备一个微信公众号,并且域名JSAPI 配置接口正确,微信只能在部署在外网才能正常使用和测试;
闲话不多少说直接上代码 :
第一步:首先我们的有前端调用前端调用(实例代码)
<% if (IsWeiXinBrower) <%--这里是后端写的一个判断是否为微信浏览器的方法判断--%>
{ %>
<script src="/Scripts/jweixin-1.0.0.js?t=2016060160945"></script> <%--这个JS很重要,是微信官网的JS接口--%>
<script src="/Scripts/weixincommon.js?t=2016060160945"></script><%--这个JS就是我自己写的一个方法封装了--%>
<script type="text/javascript">
if (wx){
$(document).ready(function(){
WeiXinCommon2.WeiXinConfig();
var title = '<%= DtProductBasicInfo.Rows[0]["Productname"].ToString("") %>';
var content = title;
var link ='<%= WeiXinShareUrl %>';
var imgUrl = '<%= ShareImageUrl %>';
wx.ready(function () {
WeiXinCommon2.ShareToFriend(title, content, link, imgUrl);
WeiXinCommon2.ShareToTimeLine(title, link, imgUrl);
});
});
}
</script>
<% } %>
第二步:创建JS文件,例如:weixincommon.js,将下面的JS复制到封装的JS代码就可以了
function IsWeiXinBrowser() {
var ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == "micromessenger") {
return true;
}
else {
return false;
}
}
var WeiXinCommon2 = ({
WeiXinConfig: function () {
$.ajax({
async: false,
url: '/WeiXinInterface/WeixinInterface.ashx',
type: 'POST',
dataType: "json",
data: {
type: "GetWeiXinJSApiConfig",
url: window.location.href
},
error: function (xhr, status, err) {
},
success: function (json) {
if (json.IsSuccess) {
wx.config({
debug: false,
appId: json.appId,
timestamp: json.timestamp,
nonceStr: json.noncestr,
signature: json.signature,
jsApiList: [
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'startRecord',
'stopRecord',
'onVoiceRecordEnd',
'playVoice',
'pauseVoice',
'stopVoice',
'onVoicePlayEnd',
'uploadVoice',
'downloadVoice',
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage',
'translateVoice',
'getNetworkType',
'openLocation',
'getLocation',
'hideOptionMenu',
'showOptionMenu',
'hideMenuItems',
'showMenuItems',
'hideAllNonBaseMenuItem',
'showAllNonBaseMenuItem',
'closeWindow',
'scanQRCode',
'chooseWXPay',
'openProductSpecificView',
'addCard',
'chooseCard',
'openCard'
]
});
}
else {
}
}
});
},
ShareToFriend: function (title, desc, link, imgUrl, successFn, cancelFn, failFn) {
wx.onMenuShareAppMessage({
title: title,
desc: desc,
link: link,
imgUrl: imgUrl,
trigger: function (res) {
},
success: function (res) {
if (typeof (successFn) == "function") {
successFn();
}
},
cancel: function (res) {
if (typeof (cancelFn) == "function") {
cancelFn();
}
},
fail: function (res) {
if (typeof (failFn) == "function") {
failFn();
}
}
});
},
ShareToTimeLine: function (title, link, imgUrl, successFn, cancelFn, failFn) {
wx.onMenuShareTimeline({
title: title,
link: link,
imgUrl: imgUrl,
trigger: function (res) {
},
success: function (res) {
if (typeof (successFn) == "function") {
successFn();
}
},
cancel: function (res) {
if (typeof (cancelFn) == "function") {
cancelFn();
}
},
fail: function (res) {
if (typeof (failFn) == "function") {
failFn();
}
}
});
},
ShareToQQ: function (title, desc, link, imgUrl, completeFn, successFn, cancelFn, failFn) {
wx.onMenuShareQQ({
title: title,
desc: desc,
link: link,
imgUrl: imgUrl,
trigger: function (res) {
alert('用户点击分享到QQ');
},
complete: function (res) {
if (typeof (completeFn) == "function") {
completeFn();
}
},
success: function (res) {
if (typeof (successFn) == "function") {
successFn();
}
},
cancel: function (res) {
if (typeof (cancelFn) == "function") {
cancelFn();
}
},
fail: function (res) {
if (typeof (failFn) == "function") {
failFn();
}
}
});
},
ShareToWeiBo: function (title, desc, link, imgUrl, completeFn, successFn, cancelFn, failFn) {
wx.onMenuShareWeibo({
title: title,
desc: desc,
link: link,
imgUrl: imgUrl,
trigger: function (res) {
alert('用户点击分享到微博');
},
complete: function (res) {
if (typeof (completeFn) == "function") {
completeFn();
}
},
success: function (res) {
if (typeof (successFn) == "function") {
successFn();
}
},
cancel: function (res) {
if (typeof (cancelFn) == "function") {
cancelFn();
}
},
fail: function (res) {
if (typeof (failFn) == "function") {
failFn();
}
}
});
},
HideOptionMenu: function () {
wx.hideOptionMenu();
},
ShowOptionMenu: function () {
wx.showOptionMenu();
},
HideMenuItems: function (menuList) {
wx.hideMenuItems({
menuList: menuList,
success: function (res) {
},
fail: function (res) {
}
});
},
ShowMenuItems: function (menuList) {
wx.showMenuItems({
menuList: menuList,
success: function (res) {
},
fail: function (res) {
}
});
},
HideAllNonBaseMenuItems: function(){
wx.hideAllNonBaseMenuItem({
success: function () {
alert('已隐藏所有非基本菜单项');
}
});
},
ShowAllNonBaseMenuItems: function () {
wx.showAllNonBaseMenuItem({
success: function () {
alert('已显示所有非基本菜单项');
}
});
},
CloseWindow: function () {
wx.closeWindow();
}
});
第三步:后端代码(.NET)
protected string GetWeiXinJSApiConfig(HttpContext context)
{
object result;
string url = context.Request["url"].ToString("");
int lastIndexOfSharpChar = url.LastIndexOf('#');
if (lastIndexOfSharpChar >= 0)
url = url.Remove(lastIndexOfSharpChar);
DataRow dr = DevInfoBLL.LoadDeveloperInfo();
string appId = dr != null ? dr["AppId"].ToString("") : "";
string appSecret = dr != null ? dr["AppSecret"].ToString("") : "";
if (string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(appSecret)) {
result = new {
IsSuccess = false,
Message = "未录入开发者信息!",
};
}
else {
long timestamp = DateTime.Now.ToTimestamp();
string noncestr = GetNonceStr();
string signature = "";
if (!string.IsNullOrEmpty(appId) && !string.IsNullOrEmpty(appSecret)) {
signature = WeiXinMenuHelper.GetJSApiTicketSignature(appId, appSecret, noncestr, timestamp, url);
result = new {
IsSuccess = true,
Message = "",
appId = appId,
appSecret = appSecret,
timestamp = timestamp,
noncestr = noncestr,
signature = signature
};
}
else {
result = new {
IsSuccess = false,
Message = "未取得微信配置信息!",
};
}
}
return result.ToJson();
}
public static string GetJSApiTicketSignature(string appId, string appSecret, string noncestr, long timesStamp, string url)
{
string jsApiTicket = GetJSApiTicket(appId, appSecret);
string hashSource = string.Format("jsapi_ticket={0}&noncestr={1}×tamp={2}&url={3}",
jsApiTicket, noncestr, timesStamp, url);
System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(hashSource);
byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
str_sha1_out = str_sha1_out.Replace("-", "");
return str_sha1_out;
}
public string GetNonceStr()
{
string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sbResult = new StringBuilder();
Random random = new Random(chars.Length);
for (int i = 0; i < 32; i++) {
sbResult.Append(chars[random.Next(chars.Length)]);
}
return sbResult.ToString();
}
以上是实现的关键代码,可以根据自己的理解适当封装,来满足自己的需求,后续会有更多的微信JS-SDK接口实现陆续更新,请持续关注。。。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)