国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Simple implementation of the WeChat sharing background interface
Home WeChat Applet WeChat Development The latest general process of implementing the WeChat sharing back-end interface

The latest general process of implementing the WeChat sharing back-end interface

Aug 01, 2018 am 11:36 AM

Simple implementation of the WeChat sharing background interface

The general process of this interface is: user creation timestamp, random string, and the URL of the page that currently needs to be shared Three variables, then use your appid and APPsecret as request parameters to obtain access_token, then obtain jsapi_ticket based on access_token, and encrypt and verify the obtained jsapi-ticket and sign the three variables you created. Note that the signature process is as follows The key value ASCII code is sorted in ascending order and the data is encapsulated in json format and sent to the front-end JS page. The specific procedure is as follows;

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);
        //這里是保存點擊次數(shù)
        //沒有數(shù)據(jù)庫的情況下 保證服務重啟后點擊次數(shù)不清零
        //利用線程鎖 使用IO流 對點擊次數(shù)進行修改保存
             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);//點擊次數(shù)
        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);
        }
    }
}

Get access_token; During the development process, it should be noted that WeChat limits access_token every day in order to reduce the pressure on access to the server. The number of times of generation and the duration of use;
Since the time limit is 7200s, we made a judgment and used the same token 2 hours after generating a token;
This is just a small interface, so we chose to change the most recent generation time And the token is stored as a static variable,

    /**
     * 微信分享,獲取access_token
     */
    private String getWeiXinAccessToken(String[] wxInfo) throws Exception {
         //得到當前時間
        long current_time = System.currentTimeMillis();
        // 每次調(diào)用,判斷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;
    }

Get jsapiTicket based on access_token

    /**
     * 微信分享,獲取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 remote call

    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 失?。?quot;, e);
        } finally {// 關閉連接,釋放資源
            httpclient.getConnectionManager().shutdown();
        }
        return result;
    }

returns successfully

 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}

Related articles:

Implement Node.js in the WeChat JS-SDK backend interface

How to call the interface of the shared page on the WeChat h5 page

javascript - What is the interface address for sharing to WeChat WeChat Moments QQ friends on the mobile phone?

Related videos:

WeChat public platform interface secondary development video tutorial

The above is the detailed content of The latest general process of implementing the WeChat sharing back-end interface. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)