微信接口開發,包含服務端(採用.net),前端js
//服務端
namespace EatWorld
{
public partial class Default : System.Web.UI.Page
{
string Token = System.Configuration.ConfigurationManager.AppSettings["Token"];
string appid = System.Configuration.ConfigurationManager.AppSettings["appid"];
string appsecret = System.Configuration.ConfigurationManager.AppSettings["appsecret"];
/// <summary>
/// 用戶登陸驗證 驗證成功後返回用戶json信息
/// </summary>
public void User_Redirect_Uri()
{
if (!string.IsNullOrEmpty(Request["code"]))
{
string userCode = Request["code"].ToString();
string postStr = GetWXAPI_Data("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + userCode + "&grant_type=authorization_code");
WXUserInfo wxu = JsonConvert.DeserializeObject(postStr, typeof(WXUserInfo)) as WXUserInfo;
Session["WXUserInfo"] = wxu;
Session.Timeout = 60 * 2;
WriteText(wxu.refresh_token);
Response.Redirect("/PhoneCarmeor.htm?refresh_token=" + DateTime.Now.ToString("yyyy-MM-dd") + "|" + wxu.refresh_token);
//Response.Write("<script>localStorage['refresh_token']='" + DateTime.Now.ToString("yyyy-MM-dd") + "|" + wxu.refresh_token + "';location.href='" + Request.Url + "';</script>");
}
else
{
string refresh_token = Request["refresh_token"].ToString().Split('|')[0];
if (Session["WXUserInfo"] == null)
{
string postStr = GetWXAPI_Data("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appid + "&grant_type=refresh_token&refresh_token=" + refresh_token);
WXUserInfo wxu = JsonConvert.DeserializeObject(postStr, typeof(WXUserInfo)) as WXUserInfo;
Session["WXUserInfo"] = wxu;
}
WXUserInfo.UserInfo = Session["WXUserInfo"] as WXUserInfo;
string postUserStr = GetWXAPI_Data("https://api.weixin.qq.com/sns/userinfo?access_token=" + WXUserInfo.UserInfo.access_token + "&openid=" + WXUserInfo.UserInfo.openid + "&lang=zh_CN");
WXUserInfo.UserDetailed = JsonConvert.DeserializeObject(postUserStr, typeof(WXUserDetailed)) as WXUserDetailed;
Response.Clear();
Response.Write(JsonConvert.SerializeObject(WXUserInfo.UserDetailed));
Response.End();
Response.Flush();
}
}
/// <summary>
/// 建立全局Token文件 而且返回Token
/// </summary>
/// <param name="pamFileUrl"></param>
/// <param name="pamSeconds"></param>
/// <param name="pamAccessToken"></param>
public string CreateAccessToken(string pamFileUrl, string pamColumnName)
{
//文件存放地址
pamFileUrl = Server.MapPath(pamFileUrl);
//當前操做
string Operating = "Add";
//數據集
DataSet ds = new DataSet();
//若是磁盤存在此文件則直接加載到數據集上 不然 就從新建立
if (!File.Exists(pamFileUrl))
ds = new Access_Token();
else
ds.ReadXml(pamFileUrl);
//篩選當前數據集中ColumnName是當前key的行
DataView dv = ds.Tables[0].DefaultView;
dv.RowFilter = "ColumnName='" + pamColumnName + "' and ColumnValue<>''";
DataRow dr = null;
//判斷是否找到當前ColumnName的行 若是有 臨時認爲是修改 不然是添加
if (dv.Count > 0)
{
dr = dv[0].Row;
Operating = "Update";
}
else
dr = ds.Tables[0].NewRow();
//獲取當前時間
DateTime nowdatetime = DateTime.Now;
DateTime enddatetime = DateTime.Now;
//若是是修改的話 則取出當前行中的時間
if (Operating == "Update")
enddatetime = new DateTime(long.Parse(dr[1].ToString()));
//獲取當前時間和修改時間的差
TimeSpan nowtimespan = new TimeSpan(nowdatetime.Ticks);
TimeSpan endtimespan = new TimeSpan(enddatetime.Ticks);
TimeSpan timespan = nowtimespan.Subtract(endtimespan).Duration();
//操做爲添加或者生成的值失效後觸發
if (Operating == "Add" || timespan.TotalSeconds >= 7200)
{
//定義變量 獲取當前秒,
//和從微信API中獲取的值一併保存到文件中,
//用來檢測是否已失效
long pamSeconds = DateTime.Now.Ticks;
//訪問微信API接口返回的值
string postStr = "";
//微信反饋信息臨時儲存類
WXHelper helper;
//把當前秒和ColumnName加到文件裏
dr[1] = pamSeconds;
dr[0] = pamColumnName;
//根據獲取ColumnName名稱 訪問相應的接口 並存儲相應的值
switch (pamColumnName)
{
case "globle_access_token":
postStr = GetWXAPI_Data("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret);
helper = Newtonsoft.Json.JsonConvert.DeserializeObject(postStr, typeof(WXHelper)) as WXHelper;
dr[2] = helper.access_token;
break;
case "jsapi_ticket":
postStr = GetWXAPI_Data("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + Request["ACCESS_TOKEN"].ToString() + "&type=jsapi");
helper = Newtonsoft.Json.JsonConvert.DeserializeObject(postStr, typeof(WXHelper)) as WXHelper;
dr[2] = helper.ticket;
break;
}
if (Operating == "Update")
{
ds.Tables[0].AcceptChanges();
ds.WriteXml(pamFileUrl, XmlWriteMode.WriteSchema);
}
else
{
ds.Tables[0].Rows.Add(dr);
ds.WriteXml(pamFileUrl, XmlWriteMode.WriteSchema);
}
}
//返回當前接口返回的值
return dr[2].ToString();
}
/// <summary>
/// 根據地址遠程訪問web服務器
/// </summary>
/// <param name="pamUrl">要訪問的地址</param>
/// <returns></returns>
public string GetWXAPI_Data(string pamUrl)
{
WebRequest webReq = WebRequest.Create(pamUrl);
//接收遠程WEB服務器發回的響應
WebResponse webRes = webReq.GetResponse();
//獲取文件長度
long fileLength = webRes.ContentLength;
//建立一個文件流,接收返回的流信息
Stream srm = webRes.GetResponseStream();
//使用特殊編碼讀取流信息
StreamReader srmReader = new StreamReader(srm);
//定義緩衝區
byte[] bufferbyte = new byte[fileLength];
//緩衝區長度
int allByte = (int)bufferbyte.Length;
int startByte = 0;
//讀取緩衝區內容
while (fileLength > 0)
{
int downByte = srm.Read(bufferbyte, startByte, allByte);
if (downByte == 0) { break; };
startByte += downByte;
allByte -= downByte;
}
string postStr = Encoding.UTF8.GetString(bufferbyte);
return postStr;
}
protected void Page_Load(object sender, EventArgs e)
{
WriteText("開放平臺進來了!\r\n");
WriteText(Request.HttpMethod.ToLower());
if (!string.IsNullOrEmpty(Request["Method"]))
{
switch (Request["Method"].ToString())
{
case "createToken":
if (!Directory.Exists(Server.MapPath("/CDT/XML")))
Directory.CreateDirectory(Server.MapPath("/CDT/XML"));
string token = CreateAccessToken("/CDT/XML/Access_Token.xml", "globle_access_token");
Response.Clear();
Response.Write(token);
Response.End();
Response.Flush();
break;
case "getJsapi_ticket":
if (!Directory.Exists(Server.MapPath("/CDT/XML")))
Directory.CreateDirectory(Server.MapPath("/CDT/XML"));
string jsapi_ticket = CreateAccessToken("/CDT/XML/Access_Token.xml", "jsapi_ticket");
Response.Clear();
Response.Write(jsapi_ticket);
Response.End();
Response.Flush();
break;
case "User_Redirect_Uri":
User_Redirect_Uri();
break;
case "login":
Valid();
break;
}
}
if (IsPostBack)
return;
string postStr = "";
if (Request.HttpMethod.ToLower() == "post")
{
Stream s = System.Web.HttpContext.Current.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
postStr = Encoding.UTF8.GetString(b);
WriteText("開始");
if (!string.IsNullOrEmpty(postStr))
{
WriteText("進來了1");
//封裝請求類
XmlDocument doc = new XmlDocument();
doc.LoadXml(postStr);
XmlElement rootElement = doc.DocumentElement;
XmlNode MsgType = rootElement.SelectSingleNode("MsgType");
WxUser.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;
WxUser.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;
WxUser.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;
WxUser.MsgType = MsgType.InnerText;
WriteTxt("----------粉絲髮送過來的消息,消息類型:" + WxUser.MsgType + "----------:" + WxUser.FromUserName);
if (WxUser.MsgType == "text")
{
WxUser.Content = rootElement.SelectSingleNode("Content").InnerText;
WxUser.MsgId = rootElement.SelectSingleNode("MsgId").InnerText;
WriteText(rootElement.SelectSingleNode("Content").InnerText);
ResponseMsg();
}
else if (WxUser.MsgType == "location")
{
WxUser.Location_X = rootElement.SelectSingleNode("Location_X").InnerText;
WxUser.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText;
WxUser.Scale = rootElement.SelectSingleNode("Scale").InnerText;
WxUser.Label = rootElement.SelectSingleNode("Label").InnerText;
}
else if (WxUser.MsgType == "image")
{
WxUser.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;
ResponseMsg();
}
else if (WxUser.MsgType == "event")
{
WxUser.Wxevent = rootElement.SelectSingleNode("Event").InnerText;
WxUser.EventKey = rootElement.SelectSingleNode("EventKey").InnerText;
}
//WriteText("我終於獲取到用戶的openid了 哈哈哈 這是FromUserName: " + user.FromUserName + " ,這是ToUserName: " + user.ToUserName);
//Response.Write("<script>alert('" + user.ToUserName + "');</script>");
//WxUser u = Session["WxUser"] as WxUser;
//WriteTxt("----------粉絲髮送過來的消息,消息類型:" + u.MsgType + "----------:" + u.ToUserName);
//Session["UserId"] =
string UserId = FuncUser_CDS.FuncUser_CreateOne(WxUser.FromUserName, "", "", "", 0);
WxUser.UserId = Convert.ToInt32(UserId);
//Session["UserId"] = WxUser.UserId;
//WriteText("UserIdDown1:" + UserId);
//Response.Write("<script>alert('" + UserId + "');return;</script>");
WriteText("進來了");
}
}
else
{
Response.Write("沒進來");
//Valid();
}
if (!string.IsNullOrEmpty(WxUser.UserId.ToString()) && WxUser.UserId > 0)
{
SessionWx.Add(WxUser.FromUserName, WxUser.UserId);
}
//WriteText(WxUser.FromUserName + ",UserId=" + UserId);
if (WxUser.FromUserName != "")
{
//NavType=
if (!string.IsNullOrEmpty(Request["NavType"]))
{
switch (Request["NavType"])
{
case "BusinessView":
Response.Redirect("/Business_View.html?BusinessKey=" + Request["BusinessKey"]);
break;
}
}
else
{
Response.Redirect("/Business_List.html");
}
}
//}
//Response.Write("<script>alert('抱歉,由於網絡問題獲取用戶資料失敗!請從新點餐!');return;</script>");
}
/// <summary>
/// 調試寫入文件
/// </summary>
/// <param name="context"></param>
public void WriteText(string context)
{
FileStream fs = new FileStream(Server.MapPath("/TextFile1.txt").ToString(), FileMode.Append);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
sw.Write(context);
sw.Close();
fs.Close();
}
/// <summary>
/// 驗證微信簽名
/// </summary>
/// * 將token、timestamp、nonce三個參數進行字典序排序
/// * 將三個參數字符串拼接成一個字符串進行sha1加密
/// * 開發者得到加密後的字符串可與signature對比,標識該請求來源於微信。
/// <returns></returns>
private bool CheckSignature()
{
string signature = Request.QueryString["signature"];
string timestamp = Request.QueryString["timestamp"];
string nonce = Request.QueryString["nonce"];
string[] ArrTmp = { Token, timestamp, nonce };
Array.Sort(ArrTmp); //字典排序
string tmpStr = string.Join("", ArrTmp);
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
tmpStr = tmpStr.ToLower();
if (tmpStr == signature)
{
return true;
}
else
{
return false;
}
}
private void Valid()
{
string echoStr = Request.QueryString["echoStr"];
if (CheckSignature())
{
if (!string.IsNullOrEmpty(echoStr))
{
Response.Clear();
Response.Write(echoStr);
Response.Flush();
Response.End();
}
}
}
/// <summary>
/// 回覆消息(微信信息返回)
/// </summary>
/// <param name="weixinXML"></param>
private void ResponseMsg(/*WxUser user*/)
{
string resxml = "<xml><ToUserName><![CDATA[" + WxUser.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + WxUser.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime>";
try
{
if (WxUser.MsgType == "text")
{
int count = 0;
if (WxUser.Content.Trim() == "單圖")
{
count = 1;
resxml += "<MsgType><![CDATA[news]]></MsgType><ArticleCount>" + count + "</ArticleCount><Articles>";
resxml += "<item><Title><![CDATA[這裏是標題]]></Title><Description><![CDATA[這裏是描述,當是單圖文的時候描述纔會展現]]></Description><PicUrl><![CDATA[http://imgsrc.baidu.com/product_name/pic/item/32374836acaf2edd470a31508d1001e93801934a.jpg]]></PicUrl><Url><![CDATA[http://www.baidu.com]]></Url></item>";//URL是點擊以後跳轉去那裏,這裏跳轉到百度
resxml += "</Articles><FuncFlag>0</FuncFlag></xml>";
}
else if (WxUser.Content.Trim() == "多圖")
{
count = 10;
resxml += "<MsgType><![CDATA[news]]></MsgType><ArticleCount>" + count + "</ArticleCount><Articles>";
for (int i = 0; i < count; i++)
{
resxml += "<item><Title><![CDATA[這裏是標題" + (i + 1) + "]]></Title><Description><![CDATA[這裏是描述,當是單圖文的時候描述纔會展現]]></Description><PicUrl><![CDATA[http://imgsrc.baidu.com/product_name/pic/item/32374836acaf2edd470a31508d1001e93801934a.jpg]]></PicUrl><Url><![CDATA[http://www.baidu.com]]></Url></item>";//URL是點擊以後跳轉去那裏,這裏跳轉到百度
}
resxml += "</Articles><FuncFlag>0</FuncFlag></xml>";
}
else
{
if (WxUser.Content == "1234")
{
resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[http://17haidai.cn/IFrame_Jb.htm]]></Content><FuncFlag>0</FuncFlag></xml>";
WriteText("\n\n返回給粉絲的消息:" + resxml);
System.Web.HttpContext.Current.Response.Write(resxml);
System.Web.HttpContext.Current.Response.End();
Response.End();
}
}
}
else if (WxUser.MsgType == "location")
{
resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你發過來的是地理消息\n哈哈]]></Content><FuncFlag>0</FuncFlag></xml>";
}
else if (WxUser.MsgType == "image")
{
resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你發一張圖片過來我怎麼識別啊,你覺得我有眼睛啊\n哈哈]]></Content><FuncFlag>0</FuncFlag></xml>";
}
else if (WxUser.MsgType == "event")
{
if (WxUser.Wxevent == "unsubscribe")
{
//取消關注
}
else
{
//新增關注
resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[謝謝你關注我。]]></Content><FuncFlag>0</FuncFlag></xml>";
}
}
}
catch (Exception ex)
{
WriteTxt("異常:" + ex.Message);
}
DataView dv = ReplyTemp_CDS.ReplyTemp_ByKeyWordGet(WxUser.Content).Tables[0].DefaultView;
if (dv.Count > 0)
{
StringBuilder sb = new StringBuilder();
sb.Append(" <xml> ");
sb.Append(" <ToUserName><![CDATA[" + WxUser.FromUserName + "]]></ToUserName> ");
sb.Append(" <FromUserName><![CDATA[" + WxUser.ToUserName + "]]></FromUserName> ");
sb.Append(" <CreateTime>" + WxUser.CreateTime + "</CreateTime> ");
sb.Append(" <MsgType><![CDATA[news]]></MsgType> ");
sb.Append(" <ArticleCount>1</ArticleCount> ");
sb.Append(" <Articles> ");
sb.Append(" <item> ");
sb.Append(" <Title><![CDATA[" + dv[0]["TempTitle"].ToString() + "]]></Title> ");
sb.Append(" <Description><![CDATA[" + dv[0]["TempContent"].ToString() + "]]></Description> ");
sb.Append(" <PicUrl><![CDATA[http://eat.onkm.net/asd/" + dv[0]["BusinessKey"].ToString() + "/ReplyTemp/img/" + dv[0]["TempId"].ToString() + "." + ((enmHasPic)dv[0]["TempExtend"]).ToString() + "]]></PicUrl>");
//sb.Append(" <PicUrl><![CDATA[http://eat.onkm.net/asd/GLMyinyuect/ReplyTemp/img/1.jpg]]></PicUrl>");
WriteText(dv[0]["TempExtend"].ToString());
string pamTempUrl = Convert.ToInt32(dv[0]["TempType"]) == Convert.ToInt32(enmReplyTempType.內部連接) ? "http://eat.onkm.net/Default.aspx?BusinessKey=" + dv[0]["BusinessKey"].ToString() + "&TypeId=0&NavType=BusinessView" : dv[0]["TempUrl"].ToString();
sb.Append(" <Url><![CDATA[" + pamTempUrl + "]]></Url> ");
sb.Append(" </item> ");
sb.Append(" </Articles> ");
sb.Append(" </xml> ");
System.Web.HttpContext.Current.Response.Write(sb.ToString());
System.Web.HttpContext.Current.Response.End();
Response.End();
}
}
/// <summary>
/// unix時間轉換爲datetime
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
private DateTime UnixTimeToTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
/// <summary>
/// datetime轉換爲unixtime
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
private int ConvertDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}
/// <summary>
/// 記錄bug,以便調試
/// </summary>
///
/// <returns></returns>
public bool WriteTxt(string str)
{
try
{
FileStream fs = new FileStream(Server.MapPath("/bugLog.txt"), FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
//開始寫入
sw.WriteLine(str);
//清空緩衝區
sw.Flush();
//關閉流
sw.Close();
fs.Close();
}
catch (Exception)
{
return false;
}
return true;
}
}
//微信請求類
/// <summary>
/// 微信請求類
/// </summary>
public class WeiXinRequest
{
private string toUserName;
/// <summary>
/// 消息接收方微信號,通常爲公衆平臺帳號微信號
/// </summary>
public string ToUserName
{
get { return toUserName; }
set { toUserName = value; }
}
private string fromUserName;
/// <summary>
/// 消息發送方微信號
/// </summary>
public string FromUserName
{
get { return fromUserName; }
set { fromUserName = value; }
}
private string createTime;
/// <summary>
/// 建立時間
/// </summary>
public string CreateTime
{
get { return createTime; }
set { createTime = value; }
}
private string msgType;
/// <summary>
/// 信息類型 地理位置:location,文本消息:text,消息類型:image,音頻:voice,視頻:video,取消關注:Action
/// </summary>
public string MsgType
{
get { return msgType; }
set { msgType = value; }
}
private string content;
/// <summary>
/// 信息內容
/// </summary>
public string Content
{
get { return content; }
set { content = value; }
}
private string msgId;
/// <summary>
/// 消息ID(文本)
/// </summary>
public string MsgId
{
get { return msgId; }
set { msgId = value; }
}
private string wxevent;
/// <summary>
/// 取消關注時的Event節點
/// </summary>
public string Wxevent
{
get { return wxevent; }
set { wxevent = value; }
}
private string eventKey;
/// <summary>
/// 取消關注時的EventKey節點
/// </summary>
public string EventKey
{
get { return eventKey; }
set { eventKey = value; }
}
private string location_X;
/// <summary>
/// 地理位置緯度
/// </summary>
public string Location_X
{
get { return location_X; }
set { location_X = value; }
}
private string location_Y;
/// <summary>
/// 地理位置經度
/// </summary>
public string Location_Y
{
get { return location_Y; }
set { location_Y = value; }
}
private string scale;
/// <summary>
/// 地圖縮放大小
/// </summary>
public string Scale
{
get { return scale; }
set { scale = value; }
}
private string label;
/// <summary>
/// 地理位置信息
/// </summary>
public string Label
{
get { return label; }
set { label = value; }
}
private string picUrl;
/// <summary>
/// 圖片連接,開發者能夠用HTTP GET獲取
/// </summary>
public string PicUrl
{
get { return picUrl; }
set { picUrl = value; }
}
}
//前端
WX_Login: function (sucessUrl) {
if ((Request["code"] == "" || Request["code"] == null || Request["code"] == undefined))
location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + sky.params.appid + "&redirect_uri=" + encodeURIComponent("http://17haidai.cn/IFrame_Jb.htm?successurl=" + sucessUrl + "&BusinessKey=" + scope.BusinessKey + (Request["navType"] != null && Request["navType"] != undefined ? "&navType=share" : "") + "&TypeParent=" + (scope.TypeParent == undefined ? "" : scope.TypeParent)) + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
else
$.get("/ase/WXLogin.ashx", { "Method": "Get_UserInfo", "Wx_Method": "user_access_token", "code": Request["code"] }, function (msg) {
msg = eval("[" + msg + "]");
sky.setCookie("user_access_token", msg[0].access_token, 24);
sky.setCookie("user_refresh_token", msg[0].refresh_token, 720);
sky.setCookie("user_openId", msg[0].openid, 24);
});
},
Get_User_Access_Token: function () {
$.get("/ase/WXLogin.ashx", { "Method": "Get_UserInfo", "Wx_Method": "user_refresh_token", "user_refresh_token": sky.getCookie("user_refresh_token") }, function (msg) {
msg = eval("[" + msg + "]");
sky.setCookie("user_access_token", msg[0].access_token, 24);
sky.setCookie("user_refresh_token", msg[0].refresh_token, 720);
sky.setCookie("user_openId", msg[0].openid, 24);
});
}, Get_Globle_Access_Token: function () {
if (sky.getCookie("globle_access_token") == "") {
$.get("/ase/WXLogin.ashx", { "Method": "Get_UserInfo", "Wx_Method": "globle_access_token" }, function (msg) {
msg = eval("[" + msg + "]");
sky.setCookie("globle_access_token", msg[0].access_token, 2);
sky.Get_Jsapi_Ticket();
});
}
else
sky.Get_Jsapi_Ticket();
}, Get_Jsapi_Ticket: function () {
if (sky.getCookie("jsapi_ticket") == "")
$.get("/ase/WXLogin.ashx", { "Method": "Get_UserInfo", "Wx_Method": "jsapi_ticket", "globle_access_token": sky.getCookie("globle_access_token") }, function (msg) {
msg = eval("[" + msg + "]");
sky.setCookie("jsapi_ticket", msg[0].ticket, 2);
sky.WX_Js_Valid(sky.getCookie("jsapi_ticket"));
});
else
sky.WX_Js_Valid(sky.getCookie("jsapi_ticket"));
}, WX_Js_Valid: function (jsapi_ticket) {
var qm = sign(jsapi_ticket, location.href);
wx.config({
debug: false, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。
appId: sky.params.appid, // 必填,公衆號的惟一標識
timestamp: qm.timestamp, // 必填,生成簽名的時間戳
nonceStr: qm.nonceStr, // 必填,生成簽名的隨機串
signature: qm.signature, // 必填,簽名,見附錄1
jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'previewImage'] // 必填,須要使用的JS接口列表,全部JS接口列表見附錄2
});
},
getCookie: function (c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=")
if (c_start != -1) {
c_start = c_start + c_name.length + 1
c_end = document.cookie.indexOf(";", c_start)
if (c_end == -1) c_end = document.cookie.length
return unescape(document.cookie.substring(c_start, c_end))
}
}
return "";
}, setCookie: function (c_name, value, expiredays) {
var exdate = new Date();
exdate.setHours(exdate.getHours() + expiredays);
document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
},//調用微信js準備方法
Wx_JSRead: function (pamTitle, pamImgUrl, pamLink, pamDesp) {
//當微信js驗證成功後觸發此函數
wx.ready(function () {
// $(".loading").hide();
wx.onMenuShareTimeline({
title: pamTitle, // 分享標題
link: pamLink, // 分享連接
imgUrl: pamImgUrl, // 分享圖標
trigger: function (res) {
//alert('用戶點擊分享到朋友圈');
},
success: function () {
var sky_initComplete = setInterval(function () {
clearInterval(sky_initComplete);
sky.Alter("您已分享到朋友圈!");
var Alter_Inver = setTimeout(function () {
clearInterval(Alter_Inver);
$(".sky_alter .sky_alter_close").click();
}, 1000);
}, 1);
// alert("分享朋友圈成功");
// 用戶確認分享後執行的回調函數
},
cancel: function () {
// 用戶取消分享後執行的回調函數
},
fail: function (res) {
//alert('wx.onMenuShareTimeline:fail: ' + JSON.stringify(res));
}
});
// pamTitle = "能幫您快速定位附近商家,查看商家詳情、樓層圖、所售品牌、規劃路線,助您在海外旅行時快速找到想要的商家,是您海外旅行的必備好幫手。";
wx.onMenuShareAppMessage({
title: pamTitle, // 分享標題
desc: pamDesp, // 分享描述
link: pamLink, // 分享連接
imgUrl: pamImgUrl, // 分享圖標
type: 'link', // 分享類型,music、video或link,不填默認爲link
success: function () {
// 用戶確認分享後執行的回調函數
},
cancel: function () {
// 用戶取消分享後執行的回調函數
}
});
});
}