微信分享帶圖片,描述(asp版)
阿新 • • 發佈:2018-12-26
最近為一個aspcms網站新增微信分享帶圖片,描述的功能。
由於官方提供的程式碼裡沒有提供asp版本的原始碼,所以需要自己研究。
根據官網提供的程式碼,參考php版本的原始碼風格,我的原始碼檔案目錄為:
程式碼如下:
我們先來看access_token.asp的檔案
<%response.end%>{"access_token":"your access_token","expire_time":2018/12/26 11:56:51}
注意到了沒有前邊加了<%response.end%>就是為了非法訪問獲取這些資料,而後邊資料類似json格式,主要快取access_token和過期時間。
同理jsapi_ticket.asp
<%response.end%>{"ticket":"your ticket","expire_time":2018/12/26 11:56:52}
核心類jssdk.asp,由於asp類貌似不能像php那樣向建構函式傳入引數,所以寫在私有屬性裡
<!--#include file="sha1.asp" --> <% Session.codepage=65001 '將系統預設的gb2312編碼轉換成utf-8 Class JSSDK Private appId Private appSecret Private access_token_file Private jsapi_ticket_file ‘這裡初始化類 Private Sub Class_Initialize appId = "your appid" '註冊你的appid appSecret = "your appsecret" '註冊你的appSecret access_token_file = "access_token.asp" '快取access_token檔案 jsapi_ticket_file = "jsapi_ticket.asp" '快取jsapi_ticket檔案 End Sub '把標準時間轉換為UNIX時間戳 public Function ToUnixTime(strTime, intTimeZone) If IsEmpty(strTime) or Not IsDate(strTime) Then strTime = Now If IsEmpty(intTimeZone) or Not isNumeric(intTimeZone) Then intTimeZone = 0 ToUnixTime = DateAdd("h",-intTimeZone,strTime) ToUnixTime = DateDiff("s","1970-01-01 00:00:00", ToUnixTime) End Function '返回wx.conf所需資料 Public Function getSignPackage(url) dim nonceStr,jsapiTicket,nowtime,jsstr,returnStr nonceStr = createNonceStr(6) jsapiTicket = getJsApiTicket nowtime = ToUnixTime(now(),0) jsstr = "jsapi_ticket="&jsapiTicket&"&noncestr="&nonceStr&"×tamp="&nowtime&"&url="&url '拼接signature字串 signature = SHA1(jsstr) '加密字串 returnStr = "{""appId"": """&appId&""",""nonceStr"":"""&nonceStr&""",""timestamp"":"""&nowtime&""",""url"":"""&url&""",""signature"":"""&signature&""",""rawString"":"""&jsstr&"""}" '拼接返回字串(json)格式 getSignPackage = returnStr End Function '隨機字元函式' Private function createNonceStr(length) dim chars,str,i,seedLength chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" seedLength = Len(chars) str = "" Randomize for i=0 to length str = str + Mid(chars,Int(seedLength*Rnd)+1,1) next createNonceStr = str End Function '讀取快取檔案' Public Function get_asp_file(FileUrl,CharSet) dim str set stm=server.CreateObject("adodb.stream") stm.Type=2 '以本模式讀取 stm.mode=3 stm.charset=CharSet stm.open stm.loadfromfile server.MapPath(FileUrl) str=stm.readtext stm.Close set stm=nothing get_asp_file=str End Function '寫檔案' Public Function set_asp_file(FileUrl,Byval Str,CharSet) set stm=server.CreateObject("adodb.stream") stm.Type=2 '以本模式讀取 stm.mode=3 stm.charset=CharSet stm.open stm.WriteText str stm.SaveToFile server.MapPath(FileUrl),2 stm.flush stm.Close set stm=nothing End Function '向微信伺服器傳送請求 Public Function GetBody(weburl) Dim ObjXMLHTTP Set ObjXMLHTTP=Server.CreateObject("MSXML2.serverXMLHTTP") ObjXMLHTTP.Open "GET",weburl,False ObjXMLHTTP.send While ObjXMLHTTP.readyState <> 4 ObjXMLHTTP.waitForResponse 10000 Wend GetBody=ObjXMLHTTP.responseBody Set ObjXMLHTTP=Nothing End Function '解析微信伺服器返回的資料 Public Function BytesToBstr(body,Cset) dim objstream set objstream = Server.CreateObject("adodb.stream") objstream.Type = 1 objstream.Mode =3 objstream.Open objstream.Write body objstream.Position = 0 objstream.Type = 2 objstream.Charset = Cset BytesToBstr = objstream.ReadText objstream.Close set objstream = nothing End Function '解析字串,主要用來解析json和快取檔案 Public Function GetContent(str,start,last,n) If Instr(lcase(str),lcase(start))>0 then select case n case 0 '左右都擷取(都取前面)(去除關鍵字) GetContent=Right(str,Len(str)-Instr(lcase(str),lcase(start))-Len(start)+1) GetContent=Left(GetContent,Instr(lcase(GetContent),lcase(last))-1) case 1 '左右都擷取(都取前面)(保留關鍵字) GetContent=Right(str,Len(str)-Instr(lcase(str),lcase(start))+1) GetContent=Left(GetContent,Instr(lcase(GetContent),lcase(last))+Len(last)-1) case 2 '只往右擷取(取前面的)(去除關鍵字) GetContent=Right(str,Len(str)-Instr(lcase(str),lcase(start))-Len(start)+1) case 3 '只往右擷取(取前面的)(包含關鍵字) GetContent=Right(str,Len(str)-Instr(lcase(str),lcase(start))+1) case 4 '只往左擷取(取後面的)(包含關鍵字) GetContent=Left(str,InstrRev(lcase(str),lcase(start))+Len(start)-1) case 5 '只往左擷取(取後面的)(去除關鍵字) GetContent=Left(str,InstrRev(lcase(str),lcase(start))-1) case 6 '只往左擷取(取前面的)(包含關鍵字) GetContent=Left(str,Instr(lcase(str),lcase(start))+Len(start)-1) case 7 '只往右擷取(取後面的)(包含關鍵字) GetContent=Right(str,Len(str)-InstrRev(lcase(str),lcase(start))+1) case 8 '只往左擷取(取前面的)(去除關鍵字) GetContent=Left(str,Instr(lcase(str),lcase(start))-1) case 9 '只往右擷取(取後面的)(包含關鍵字) GetContent=Right(str,Len(str)-InstrRev(lcase(str),lcase(start))) end select Else GetContent="" End if End function '獲取access_token並快取到檔案 Public Function GetAccess_token() dim pcontent,Access_token,expire_time,url,CacheStr,CacheAccess_token,Cache_time,now_time CacheStr = get_asp_file(access_token_file,"gb2312") CacheStr = Mid(CacheStr,18)'刪除字首' Cache_time = GetContent(Mid(CacheStr ,17),"""expire_time"":","}",0) if DateDiff("s", Cache_time, now()) > 0 then '如果現在時間大於過期時間' url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" & appId &"&secret="& appSecret pcontent=BytesToBstr(GetBody(url),"utf-8") Access_token=trim(GetContent(pcontent,"""access_token"":""",""",",0)) expire_time = DateAdd("h",2,now()) '寫檔案' CacheStr = chr(60) & chr(37) & "response.end" & chr(37) & chr(62) & "{""access_token"":"""&Access_token&""",""expire_time"":"&expire_time&"}" '用chr轉碼 set_asp_file access_token_file,CacheStr,"utf-8" GetAccess_token =Access_token else GetAccess_token = GetContent(CacheStr,"""access_token"":""",""",",0) end if End Function '獲取JsApiTicket並快取到檔案 Public Function getJsApiTicket() dim pcontent,Access_token,expire_time,url,CacheStr,CacheAccess_token,Cache_time,now_time,ticket CacheStr = get_asp_file(jsapi_ticket_file,"gb2312") CacheStr = Mid(CacheStr,18)'刪除字首' Cache_time = GetContent(CacheStr,"""expire_time"":","}",0) if DateDiff("s", Cache_time, now()) > 0 then '如果現在時間大於過期時間 Access_token = GetAccess_token() url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" &Access_token pcontent=BytesToBstr(GetBody(url),"utf-8") ticket=trim(GetContent(pcontent,"""ticket"":""",""",",0)) expire_time = DateAdd("h",2,now()) '增加兩小時 '寫檔案 CacheStr = chr(60) & chr(37) & "response.end" & chr(37) & chr(62) & "{""ticket"":"""&ticket&""",""expire_time"":"&expire_time&"}" '用chr轉碼 set_asp_file jsapi_ticket_file,CacheStr,"utf-8" getJsApiTicket =ticket else getJsApiTicket = GetContent(CacheStr,"""ticket"":""",""",",0) 'getJsApiTicket = "old" end if End Function End Class %>
share.asp
<!--#include file="jssdk.asp" -->
<%
dim js,qs
qs = request.querystring("url") '獲取
set js = new JSSDK
response.write js.getSignPackage(qs)
%>
前端index.html
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <script> $(function(){ var url = location.href.split('#')[0].toString();//url不能寫死 $.ajax({ type : "get", url : "/wx/share.asp", dataType : "json", async : false, data:{url:url}, success : function(data) { wx.config({ appId: data.appId,//appId通過微信服務號後臺檢視 timestamp: data.timestamp,//生成簽名的時間戳 nonceStr: data.nonceStr,//生成簽名的隨機字串 signature: data.signature,//簽名 jsApiList: [//需要呼叫的JS介面列表 'checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo' ] }); }, error:function(xhr, status, error){ } }) var meta = document.getElementsByTagName('meta'); var share_desc = ''; for(i in meta){ if(typeof meta[i].name!="undefined"&&meta[i].name.toLowerCase()=="description"){ share_desc = meta[i].content; } } var wstitle = document.title //此處填寫分享標題 var wsdesc = share_desc; //此處填寫分享簡介(此處為網站描述) var wslink = url; //此處獲取分享連結 var wsimg = "logo.jpg"; //此處獲取分享縮圖 wx.ready(function () { // 分享到朋友圈 wx.onMenuShareTimeline({ title: wstitle, link: wslink, imgUrl: wsimg, success: function () { alert('分享成功'); }, cancel: function () { } }); // 分享給朋友 wx.onMenuShareAppMessage({ title: wstitle, desc: wsdesc, link: wslink, imgUrl: wsimg, success: function () { }, cancel: function () { } }); // 分享到QQ wx.onMenuShareQQ({ title: wstitle, desc: wsdesc, link: wslink, imgUrl: wsimg, success: function () { }, cancel: function () { } }); // 微信到騰訊微博 wx.onMenuShareWeibo({ title: wstitle, desc: wsdesc, link: wslink, imgUrl: wsimg, success: function () { }, cancel: function () { } }); // 分享到QQ空間 wx.onMenuShareQZone({ title: wstitle, desc: wsdesc, link: wslink, imgUrl: wsimg, success: function () { }, cancel: function () { } }); }); }) </script>