最新整理出的微信分享後端介面實現的大致流程

php是最好的语言
發布: 2018-08-01 11:36:36
原創
6419 人瀏覽過

微信分享後台介面簡單實作

此介面大致的流程是:使用者建立時間戳,隨機字串,目前需要分享的頁面的url三個變量,接著將自己的appid和APPsecret作為請求參數獲取access_token,再根據access_token獲取jsapi_ticket, 並將獲取的jsapi-ticket進行加密、校驗以及自己創建的三個變量進行簽名,注意簽名過程案按照key 值ASCII 碼升序排序封裝成json格式的資料傳送到前台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);
        //这里是保存点击次数
        //没有数据库的情况下 保证服务重启后点击次数不清零
        //利用线程锁 使用IO流 对点击次数进行修改保存
             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);//点击次数
        jsonObject.addProperty("errcode", 0);//
        jsonObject.addProperty("errmsg", "");//
        jsonObject.addProperty("wxuser", wxInfo[0]); // appId
        jsonObject.addProperty("timestamp", timestamp);//时间戳
        jsonObject.addProperty("noncestr", noncestr);//随机字符串
        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;這裡開發過程中要注意微信為了減輕對伺服器的存取壓力限制了access_token每天的生成次數以及使用時長;
由於限制時長為7200s 於是做了一個判斷再生成一個token後的2小時用同一個token ;
這裡僅僅只是一個小接口於是選擇將最近一次的生成時間以及token 存為靜態變量,

    /**
     * 微信分享,获取access_token
     */
    private String getWeiXinAccessToken(String[] wxInfo) throws Exception {
         //得到当前时间
        long current_time = System.currentTimeMillis();
        // 每次调用,判断expires_in是否过期,如果token时间超时,重新获取,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;
    }
登入後複製

根據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遠端呼叫

    private String httpReqExecute(String url) {
        String result = "";
        DefaultHttpClient httpclient = null;
        try {
            httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            // 执行
            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 调用微信 API 失败!", e);
        } finally {// 关闭连接,释放资源
            httpclient.getConnectionManager().shutdown();
        }
        return result;
    }
登入後複製

返回成功

 from weixin api accessToken: {"access_token":"12_9UgVn7tFVtvf_7r4Lq4V9W9-pQdZpqWxVjFsPoF3hv3J5_XfwQWqauj4n9-ZMikC1_oCp0IpBxjpZr-Ty8XzG8QMeV2QVukFz5_NP7kjAB05MX9msxRg0FlpAAMjonrrh5wxSEFfKHEc0_BDHFKjAFAXVA","expires_in":7200}

 from weixin api jsapiTicket is: {"errcode":0,"errmsg":"ok","ticket":"HoagFKDcsGMVCIY2vOjf9j_Us44Qhuo4KdgH5u8ewMjOCTUO44m1hKqgEsJYIyFR9HWrmmz-wrsb9KLdmpATRw","expires_in":7200}
登入後複製

相關文章:

實作Node.js在微信JS-SDK後端介面

#微信端h5頁面如何呼叫分享頁面的介面

javascript - 手機端的分享至微信 微信朋友圈qq好友的介面位址?

相關影片:

微信公眾平台介面二次開發影片教學

以上是最新整理出的微信分享後端介面實現的大致流程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板