這篇文章主要介紹了微信分享后臺(tái)接口簡(jiǎn)單實(shí)現(xiàn),具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
在沈北新等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供網(wǎng)站建設(shè)、成都網(wǎng)站制作 網(wǎng)站設(shè)計(jì)制作按需定制開發(fā),公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站設(shè)計(jì),營(yíng)銷型網(wǎng)站,成都外貿(mào)網(wǎng)站制作,沈北新網(wǎng)站建設(shè)費(fèi)用合理。
此接口大致的流程是:用戶創(chuàng)建時(shí)間戳,隨機(jī)字符串,當(dāng)前需要分享的頁面的url三個(gè)變量,接著將自己的appid和APPsecret作為請(qǐng)求參數(shù)獲取access_token,再根據(jù)access_token獲取jsapi_ticket, 并將獲取的jsapi-ticket進(jìn)行加密、校驗(yàn)以及自己創(chuàng)建的三個(gè)變量進(jìn)行簽名,注意簽名過程案按照 key 值 ASCII 碼升序排序封裝成json格式的數(shù)據(jù)傳送到前臺(tái)JS頁面,具體程序如下;
public class WeiXinShareAction extends HttpServlet { private static final long serialVersionUID = 1L; private Integer main_count = 888; private String flag = "1"; private Log logger = LogFactory.getLog(this.getClass()); private String filePath = "/B.txt"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonObject jsonObject = new JsonObject(); String ticket = null; String[] wxInfo = new String[] { "wx007344f87ae48300", "5442edc712b6846bdd1c058b7f2318fe" }; WeiXinUtil wxu = new WeiXinUtil(); String ticketResString; try { ticketResString = wxu.getShareJsapiTicket(wxInfo); if (StringUtils.isNotEmpty(ticketResString)) { JSONObject ticketJSONObject = JSONObject.fromObject(ticketResString); if (ticketJSONObject.getInt("errcode") == 0) { ticket = JSONObject.fromObject(ticketResString).getString("ticket"); } } } catch (Exception e) { e.printStackTrace(); } if (StringUtils.isEmpty(ticket)) { jsonObject.addProperty("errcode", 10002); jsonObject.addProperty("errmsg", "ticket_error"); this.responseWrite(jsonObject.toString(), response); return; } String noncestr = this.createNonceStr(); int timestamp = this.createTimestamp(); String requestRefererURL = request.getHeader("referer"); flag = request.getParameter("temp"); logger.info("flag--------------" + flag); //這里是保存點(diǎn)擊次數(shù) //沒有數(shù)據(jù)庫的情況下 保證服務(wù)重啟后點(diǎn)擊次數(shù)不清零 //利用線程鎖 使用IO流 對(duì)點(diǎn)擊次數(shù)進(jìn)行修改保存 Thread_readFile thf4 = new Thread_readFile(); thf4.start(); logger.warn("requestRefererURL: " + requestRefererURL); String signature = this.createSignature(noncestr, ticket, timestamp, requestRefererURL); jsonObject.addProperty("countNum", main_count);//點(diǎn)擊次數(shù) jsonObject.addProperty("errcode", 0);// jsonObject.addProperty("errmsg", "");// jsonObject.addProperty("wxuser", wxInfo[0]); // appId jsonObject.addProperty("timestamp", timestamp);//時(shí)間戳 jsonObject.addProperty("noncestr", noncestr);//隨機(jī)字符串 jsonObject.addProperty("signature", signature);//簽名 response.setHeader("Access-Control-Allow-Origin", "*"); this.responseWrite(jsonObject.toString(), response); } private void responseWrite(String content, HttpServletResponse response) { try { response.setCharacterEncoding("utf-8"); response.getWriter().write(content); } catch (Exception e) { logger.error("responseWrite error in WeiXinShareAction", e); } } }
獲取access_token;這里開發(fā)過程中要注意微信為了減輕對(duì)服務(wù)器的訪問壓力 限制了access_token每天的生成次數(shù) 以及使用時(shí)長(zhǎng);
由于限制時(shí)長(zhǎng)為7200s 于是做了一個(gè)判斷 再生成一個(gè)token后的2小時(shí)用同一個(gè)token ;
這里僅僅只是一個(gè)小接口 于是選擇將 最近一次的生成時(shí)間 以及 token 存為靜態(tài)變量,
/** * 微信分享,獲取access_token */ private String getWeiXinAccessToken(String[] wxInfo) throws Exception { //得到當(dāng)前時(shí)間 long current_time = System.currentTimeMillis(); // 每次調(diào)用,判斷expires_in是否過期,如果token時(shí)間超時(shí),重新獲取,expires_in有效期為7200 if ((current_time - last_time) / 1000 >= 7200) { logger.info("第一次訪問"+current_time); logger.info("(current_time - last_time) / 1000===="+(current_time - last_time) / 1000); String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxInfo[0] + "&secret=" + wxInfo[1]; String result = this.httpReqExecute(url); this.logger.warn("from weixin api accessToken: " + result); try { last_time = current_time; if (StringUtils.isNotEmpty(result)) { // 解析respContent,并獲取其中的更新的key, accessToken = JSONObject.fromObject(result).getString("access_token"); // 保存access_token return accessToken; } } catch (Exception e) { logger.error("getAccessToken error in WeiXinShareAction", e); } }else{ logger.info("第二次訪問"+last_time); logger.info("(current_time - last_time) / 1000===="+(current_time - last_time) / 1000); logger.info("from weixin api accessToken:"+accessToken); return accessToken; } return null; }
根據(jù)access_token獲取jsapiTicket
/** * 微信分享,獲取jsapiTicket */ public String getShareJsapiTicket(String[] wxInfo) throws Exception { String access_Token = this.getWeiXinAccessToken(wxInfo); if (StringUtils.isEmpty(access_Token)) { // 獲取 accessToken 失敗 //this.logger.warn(siteId + " accessToken is empty."); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("errcode", "10000"); jsonObject.addProperty("errmsg", "access_error"); return jsonObject.toString(); } String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_Token + "&type=jsapi"; String jsapiTicket = this.httpReqExecute(url); this.logger.warn(" from weixin api jsapiTicket is: " + jsapiTicket); if (StringUtils.isNotEmpty(jsapiTicket)) { return jsapiTicket; } return null; }
Http遠(yuǎn)程調(diào)用
private String httpReqExecute(String url) { String result = ""; DefaultHttpClient httpclient = null; try { httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); // 執(zhí)行 HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null && response.getStatusLine().getStatusCode() == 200) { result = EntityUtils.toString(entity, "UTF-8"); } } catch (Exception e) { logger.error(" WeiXinShareAction 調(diào)用微信 API 失??!", e); } finally {// 關(guān)閉連接,釋放資源 httpclient.getConnectionManager().shutdown(); } return result; }
返回成功
from weixin api accessToken: {"access_token":"12_9UgVn7tFVtvf_7r4Lq4V9W9-pQdZpqWxVjFsPoF3hv3J5_XfwQWqauj4n9-ZMikC1_oCp0IpBxjpZr-Ty8XzG8QMeV2QVukFz5_NP7kjAB05MX9msxRg0FlpAAMjonrrh6wxSEFfKHEc0_BDHFKjAFAXVA","expires_in":7200} from weixin api jsapiTicket is: {"errcode":0,"errmsg":"ok","ticket":"HoagFKDcsGMVCIY2vOjf9j_Us44Qhuo4KdgH5u8ewMjOCTUO44m1hKqgEsJYIyFR9HWrmmz-wrsb9KLdmpATRw","expires_in":7200}
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“微信分享后臺(tái)接口簡(jiǎn)單實(shí)現(xiàn)”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來學(xué)習(xí)!