前端Js引用:
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript">
var data = '<%=JsApiirray %>';
data = eval("(" + data + ")");//实例化
wxconfig(data);
</script>
<script>
function wxconfig(data) {
wx.config({
// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
debug: false,
// 必填,公众号的唯一标识
appId: data.appId,
// 必填,生成签名的时间戳
timestamp: data.timestamp,
// 必填,生成签名的随机串
nonceStr: data.nonceStr,
// 必填,签名
signature: data.signature,
// 必填,需要使用的JS接口列表
jsApiList: [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo'
]
});
}
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
wx.ready(function () {
wx.checkJsApi({
jsApiList: [
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo'
]
});
var title = "上海长宽神游戏“神龟不掉线”,千万别小看它!";
var des = "我玩过了上海长宽的游戏神作“神龟不掉线”,真的比想象中更难,你快来试试并领取电影红包吧!";
wx.onMenuShareTimeline({
title: title, //分享标题
link: 'http://m.gwbnsh.net.cn/sgbdx/', //分享链接
desc: des, //分享描述
imgUrl: 'http://m.gwbnsh.net.cn/sgbdx/img/logo.png',//分享图片地址
trigger: function (res) {
//alert('用户点击分享到朋友圈');
},
success: function (res) {
$.ajax({
type: "POST",
url: "User.ashx", //处理页的相对地址
data: { isshare: 1 },
async: true,
success: function (data) {
location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF";
}
});
},
cancel: function (res) {
//alert('已取消');
}
});
wx.onMenuShareAppMessage({
title: title, //分享标题
link: 'http://m.gwbnsh.net.cn/sgbdx/', //分享链接
desc: des, //分享描述
imgUrl: 'http://m.gwbnsh.net.cn/sgbdx/img/logo.png',//分享图片地址
trigger: function (res) {
//alert('用户点击分享到朋友圈');
},
success: function (res) {
$.ajax({
type: "POST",
url: "User.ashx", //处理页的相对地址
data: { isshare: 1 },
async: true,
success: function (data) {
location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF";
}
});
},
cancel: function (res) {
//alert('已取消');
}
});
wx.onMenuShareQQ({
title: title, //分享标题
link: 'http://m.gwbnsh.net.cn/sgbdx/', //分享链接
desc: des, //分享描述
imgUrl: 'http://m.gwbnsh.net.cn/sgbdx/img/logo.png',//分享图片地址
trigger: function (res) {
//alert('用户点击分享到朋友圈');
},
success: function (res) {
$.ajax({
type: "POST",
url: "User.ashx", //处理页的相对地址
data: { isshare: 1 },
async: true,
success: function (data) {
location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF";
}
});
},
cancel: function (res) {
//alert('已取消');
}
});
wx.onMenuShareQZone({
title: title, //分享标题
link: 'http://m.gwbnsh.net.cn/sgbdx/', //分享链接
desc: des, //分享描述
imgUrl: 'http://m.gwbnsh.net.cn/sgbdx/img/logo.png',//分享图片地址
trigger: function (res) {
//alert('用户点击分享到朋友圈');
},
success: function (res) {
$.ajax({
type: "POST",
url: "User.ashx", //处理页的相对地址
data: { isshare: 1 },
async: true,
success: function (data) {
location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF";
}
});
},
cancel: function (res) {
//alert('已取消');
}
});
wx.error(function (res) {
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
alert("errorMSG:" + res);
});
});
</script>
或者
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript">
var data = '<%=JsApiirray %>';
data = eval("(" + data + ")");//实例化
wxconfig(data);
</script>
<script>
function wxconfig(data) {
wx.config({
// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
debug: false,
// 必填,公众号的唯一标识
appId: data.appId,
// 必填,生成签名的时间戳
timestamp: data.timestamp,
// 必填,生成签名的随机串
nonceStr: data.nonceStr,
// 必填,签名
signature: data.signature,
// 必填,需要使用的JS接口列表
jsApiList: [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo'
]
});
}
/*
* 注意:
* 1. 所有的JS接口只能在公众号绑定的域名下调用,公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
* 2. 如果发现在 Android 不能分享自定义内容,请到官网下载最新的包覆盖安装,Android 自定义分享接口需升级至 6.0.2.58 版本及以上。
* 3. 完整 JS-SDK 文档地址:http://mp.weixin.qq.com/wiki/7/1c97470084b73f8e224fe6d9bab1625b.html
* 如有问题请通过以下渠道反馈:
* 邮箱地址:weixin-open@qq.com
* 邮件主题:【微信JS-SDK反馈】具体问题
* 邮件内容说明:用简明的语言描述问题所在,并交代清楚遇到该问题的场景,可附上截屏图片,微信团队会尽快处理你的反馈。
*config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
*/
wx.ready(function () {
wx.checkJsApi({
jsApiList: [
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo'
],
success: function (res) {
alert(JSON.stringify(res));
}
});
var shareData = {
title: '标题',
desc: '描述',
link: '链接',
imgUrl: '图片',
trigger: function (res) {
alert('用户点击发送给朋友');
},
success: function (res) {
alert('已分享');
},
cancel: function (res) {
alert('已取消');
},
fail: function (res) {
alert(JSON.stringify(res));
}
};
wx.onMenuShareAppMessage(shareData);
wx.onMenuShareTimeline(shareData);
wx.onMenuShareQQ(shareData);
wx.onMenuShareWeibo(shareData);
});
wx.error(function (res) {
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
alert("errorMSG:" + res);
});
</script>
验证JsAPI权限配置:
#region 验证JsApi权限配置
/// <summary>
/// 获取JsApi权限配置的数组/四个参数
/// </summary>
/// <returns></returns>
public string GetJsApiInfo(string Appid, string Appsecret)
{
string timestamp = CommonMethod.ConvertDateTimeInt(DateTime.Now).ToString();//生成签名的时间戳
string nonceStr = CommonMethod.GetRandCode();//生成签名的随机串
string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri.ToString();//当前的地址
string jsapi_ticket = "";
//ticket 缓存7200秒
if (System.Web.HttpContext.Current.Session["jsapi_ticket"] == null)
{
jsapi_ticket = CommonMethod.WebRequestPostOrGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + BasicApi.GetTokenSession(Appid, Appsecret) + "&type=jsapi", "");
System.Web.HttpContext.Current.Session["jsapi_ticket"] = jsapi_ticket;
System.Web.HttpContext.Current.Session.Timeout = ;
}
else
{
jsapi_ticket = System.Web.HttpContext.Current.Session["jsapi_ticket"].ToString();
}
Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(jsapi_ticket);
jsapi_ticket = respDic["ticket"].ToString();//获取ticket
string[] ArrayList = { "jsapi_ticket=" + jsapi_ticket, "timestamp=" + timestamp, "noncestr=" + nonceStr, "url=" + url };
Array.Sort(ArrayList);
string signature = string.Join("&", ArrayList);
signature = Md5Hash(signature).ToLower();
return "{\"appId\":\"" + Appid + "\", \"timestamp\":" + timestamp + ",\"nonceStr\":\"" + nonceStr + "\",\"signature\":\"" + signature + "\"}";
}
/// <summary>
/// 32位MD5加密
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private string Md5Hash(string input)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
StringBuilder sBuilder = new StringBuilder();
for (int i = ; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
} #endregion
基础接口BasicApi.cs:
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace Web
{// <summary>
/// 基础接口
/// </summary>
public class BasicApi
{
public static string SessionAccessToken = "";//access_token缓存 其他接口的通行证 public BasicApi() { } #region 获取access_token缓存
public static string GetTokenSession(string AppID, string AppSecret)
{
string TokenSession = ""; if (System.Web.HttpContext.Current.Session[SessionAccessToken] == null)
{
TokenSession = AddTokenSession(AppID, AppSecret);
}
else
{
TokenSession = System.Web.HttpContext.Current.Session[SessionAccessToken].ToString();
} return TokenSession;
}
/// <summary>
/// 添加AccessToken缓存
/// </summary>
/// <param name="AppID"></param>
/// <param name="AppSecret"></param>
/// <returns></returns>
public static string AddTokenSession(string AppID, string AppSecret)
{
//获取AccessToken
string AccessToken = GetAccessToken(AppID, AppSecret);
HttpContext.Current.Session[SessionAccessToken] = AccessToken;
HttpContext.Current.Session.Timeout = ;
return AccessToken;
} /// <summary>
/// 获取AccessToken
/// </summary>
/// <param name="AppID"></param>
/// <param name="AppSecret"></param>
/// <returns></returns>
public static string GetAccessToken(string AppID, string AppSecret)
{
JavaScriptSerializer Jss = new JavaScriptSerializer();
string respText = CommonMethod.WebRequestPostOrGet(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppID, AppSecret), "");
Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
string accessToken = respDic["access_token"].ToString();
return accessToken;
}
/// <summary>
/// 用code换取获取用户信息(包括非关注用户的)
/// </summary>
/// <param name="openid"></param>
/// <param name="access_token"></param>
/// <returns></returns>
public static JObject GetUserInfo(string openid, string access_token)
{
JavaScriptSerializer Jss = new JavaScriptSerializer();
string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", access_token, openid);
WebClient wc = new WebClient();
byte[] bytes = wc.DownloadData(url);
wc.Encoding = Encoding.UTF8;
string jsonText = Encoding.UTF8.GetString(bytes);
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
return jo;
}
#endregion
}
}
通用方法CommonMethod.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web; namespace Web
{
/// <summary>
/// 通用方法类
/// </summary>
public class CommonMethod
{
#region Post/Get提交调用抓取
/// <summary>
/// Post/get 提交调用抓取
/// </summary>
/// <param name="url">提交地址</param>
/// <param name="param">参数</param>
/// <returns>string</returns>
public static string WebRequestPostOrGet(string sUrl, string sParam)
{
byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam); Uri uriurl = new Uri(sUrl);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param);
req.Method = "Post";
req.Timeout = * ;
req.ContentType = "application/x-www-form-urlencoded;";
req.ContentLength = bt.Length; using (Stream reqStream = req.GetRequestStream())//using 使用可以释放using段内的内存
{
reqStream.Write(bt, , bt.Length);
reqStream.Flush();
}
try
{
using (WebResponse res = req.GetResponse())
{
//在这里对接收到的页面内容进行处理 Stream resStream = res.GetResponseStream(); StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8); string resLine; System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder(); while ((resLine = resStreamReader.ReadLine()) != null)
{
resStringBuilder.Append(resLine + System.Environment.NewLine);
} resStream.Close();
resStreamReader.Close(); return resStringBuilder.ToString();
}
}
catch (Exception ex)
{
return ex.Message;//url错误时候回报错
}
}
#endregion Post/Get提交调用抓取 #region unix/datatime 时间转换
/// <summary>
/// unix时间转换为datetime
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime UnixTimeToTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(, , ));
long lTime = long.Parse(timeStamp + "");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
} /// <summary>
/// datetime转换为unixtime
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static int ConvertDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(, , ));
return (int)(time - startTime).TotalSeconds;
}
#endregion #region 记录bug,以便调试
/// <summary>
/// 记录bug,以便调试
/// </summary>
public static bool WriteTxt(string str)
{
try
{
string LogPath = HttpContext.Current.Server.MapPath("/err_log/");
if (!Directory.Exists(LogPath))
{
Directory.CreateDirectory(LogPath);
}
FileStream FileStream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("/err_log//lwf_" + DateTime.Now.ToLongDateString() + "_.txt"), FileMode.Append);
StreamWriter StreamWriter = new StreamWriter(FileStream);
//开始写入
StreamWriter.WriteLine(str);
//清空缓冲区
StreamWriter.Flush();
//关闭流
StreamWriter.Close();
FileStream.Close();
}
catch (Exception)
{
return false;
}
return true;
}
#endregion #region 生成随机字符
/// <summary>
/// 生成随机字符
/// </summary>
/// <param name="iLength">生成字符串的长度</param>
/// <returns>返回随机字符串</returns>
public static string GetRandCode(int iLength)
{
string sCode = "";
if (iLength == )
{
iLength = ;
}
string codeSerial = "0,1,2,3,4,5,6,7,8,9,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";
string[] arr = codeSerial.Split(',');
int randValue = -;
Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
for (int i = ; i < iLength; i++)
{
randValue = rand.Next(, arr.Length - );
sCode += arr[randValue];
}
return sCode;
}
#endregion
}
}
附件为源码:微信分享Demo