利用JS-SDK微信分享介面呼叫(後端.NET)

NO IMAGE

一直都想研究一下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 %>';//<%--<%= QRImageUrl %>--%>
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, // 開啟除錯模式,呼叫的所有api的返回值會在客戶端alert出來,若要檢視傳入的引數,可以在pc端開啟,引數資訊會通過log打出,僅在pc端時才會列印。
appId: json.appId, // 必填,公眾號的唯一標識
timestamp: json.timestamp, // 必填,生成簽名的時間戳
nonceStr: json.noncestr, // 必填,生成簽名的隨機串
signature: json.signature,// 必填,簽名,見附錄1
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'
] // 必填,需要使用的JS介面列表,所有JS介面列表見附錄2
});
}
else {
//alert(json.Message);
}
}
});
},
//分享給朋友
ShareToFriend: function (title, desc, link, imgUrl, successFn, cancelFn, failFn) {
wx.onMenuShareAppMessage({
title: title,
desc: desc,
link: link,
imgUrl: imgUrl,
trigger: function (res) {
// 不要嘗試在trigger中使用ajax非同步請求修改本次分享的內容,因為客戶端分享操作是一個同步操作,這時候使用ajax的回包會還沒有返回
//alert('使用者點選傳送給朋友');
},
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) {
// 不要嘗試在trigger中使用ajax非同步請求修改本次分享的內容,因為客戶端分享操作是一個同步操作,這時候使用ajax的回包會還沒有返回
//alert('使用者點選分享到朋友圈');
},
success: function (res) {
if (typeof (successFn) == "function") {
successFn();
}
},
cancel: function (res) {
if (typeof (cancelFn) == "function") {
cancelFn();
}
},
fail: function (res) {
//alert(JSON.stringify(res));
if (typeof (failFn) == "function") {
failFn();
}
}
});
},
//分享至QQ
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,
//[
//  'menuItem:readMode', // 閱讀模式
//  'menuItem:share:timeline', // 分享到朋友圈
//  'menuItem:copyUrl' // 複製連結
//],
success: function (res) {
//alert('已隱藏“閱讀模式”,“分享到朋友圈”,“複製連結”等按鈕');
},
fail: function (res) {
//alert(JSON.stringify(res));
}
});
},
//批量顯示選單項
ShowMenuItems: function (menuList) {
wx.showMenuItems({
menuList: menuList,
//[
//  'menuItem:readMode', // 閱讀模式
//  'menuItem:share:timeline', // 分享到朋友圈
//  'menuItem:copyUrl', // 複製連結
//  'menuItem:profile', // 檢視公眾號(已新增)
//  'menuItem:addContact' // 檢視公眾號(未新增)
//],
success: function (res) {
//alert('已顯示“閱讀模式”,“分享到朋友圈”,“複製連結”等按鈕');
},
fail: function (res) {
//alert(JSON.stringify(res));
}
});
},
//隱藏所有非基本選單項
HideAllNonBaseMenuItems: function(){
wx.hideAllNonBaseMenuItem({
success: function () {
alert('已隱藏所有非基本選單項');
}
});
},
//顯示所有被隱藏的非基本選單項
ShowAllNonBaseMenuItems: function () {
wx.showAllNonBaseMenuItem({
success: function () {
alert('已顯示所有非基本選單項');
}
});
},
//關閉當前視窗
CloseWindow: function () {
wx.closeWindow();
}
});

第三步:後端程式碼(.NET)

      /// <summary>
/// 取得JSApi配置
/// </summary>
/// <returns></returns>
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();
}
/// <summary>
/// 取得微信JSApi簽名
/// </summary>
/// <returns></returns>
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}&timestamp={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;
}
/// <summary>
/// 取得nonceStr
/// </summary>
/// <returns></returns>
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介面實現陸續更新,請持續關注。。。