WeChat development method to determine whether the current client supports the specified js interface

高洛峰
Release: 2017-03-26 14:55:32
Original
1861 people have browsed it

Due to the use of WeChatjsapiInterface has permission to use, so we need to determine whether the client supports the js interface.

Basic interface, determine whether the current client version supports the specified JS Interface

First, jsapi.jspCode

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>微信jsapi测试-V型知识库</title>
    <meta name="viewport" content="width=320.1,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
   <script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"> </script> 
</head>
  <body>
  <center><h3>欢迎来到微信jsapi测试界面-V型知识库</h3></center>
  <br>
     <p>timestamp:${ timestamp}</p>  
     <p>nonceStr:${ nonceStr}</p>  
     <p>signature:${ signature}</p>  
     <p>appId:${ appId}</p>  
     <!--   
    <input type="button" value="upload" onclick="uploadImg();"/>  
    <input type="button" value="获取当前位置" onclick="getLocation();"/>  
     -->
     <p>基础接口之判断当前客户端是否支持指定的js接口</p>   
     <input type="button" value="checkJSAPI" id="checkJsApi">
  <br>
  <script type="text/javascript">
  wx.config({  
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。  
    appId: &#39;${appId}&#39;, // 必填,公众号的唯一标识  
    timestamp: &#39;${ timestamp}&#39; , // 必填,生成签名的时间戳  
    nonceStr: &#39;${ nonceStr}&#39;, // 必填,生成签名的随机串  
    signature: &#39;${ signature}&#39;,// 必填,签名,  
    jsApiList: [&#39;chooseImage&#39;,&#39;getLocation&#39;,&#39;openLocation&#39;] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2  
});  
wx.ready(function(){  
    // 1 判断当前版本是否支持指定 JS 接口,支持批量判断
  document.querySelector(&#39;#checkJsApi&#39;).onclick = function () {
    wx.checkJsApi({
      jsApiList: [
        &#39;getNetworkType&#39;,
        &#39;previewImage&#39;
      ],
      success: function (res) {
        alert(JSON.stringify(res));
      }
    });
  };
});  
 //初始化jsapi接口 状态
wx.error(function (res) {
  alert("调用微信jsapi返回的状态:"+res.errMsg);
});
 </script>
  </body>
</html>
Copy after login


##Click the buttoncheckJSAPI will trigger the method in the wx.ready(function(){}) method body, and a status of whether it is supported will pop up in the interface.

Four necessary parameters in the web page, as shown in the table below

Parameter nameDescriptionappIdRequired, the unique identifier of the official account timestampRequired, generate the timestamp of the signature nonceStrRequired, generate the random string of the signature signatureRequired, signature

So where do these four parameters come from? Please see the second step below

##Second, get appId, timestamp, nonceStr, signature

# #Before we jump to the jsapi.jsp interface, we must obtain the above four parameters to successfully call the WeChat jsapi interface. In other words, the above four parameters are the credentials for calling the WeChat jsapi interface, and appid is the id of the application. , can be viewed on the WeChat public platform. The remaining three parameters must be obtained according to the signature algorithm provided by WeChat.

#Click the link in the public account to jump. To the jsapi.jsp interface, the user clicks this link address in the official account to jump to the jsapi.jsp interface. We must obtain the above three parameters in

wxJsAPIServlet and store the parameters in the request

object, and then the jsp interface is taken out as follows:

#

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

System.out.println("wxJSAPI====================");

String jsapi_ticket =JsapiTicketUtil.getJSApiTicket();;

<a href="http://www.php.cn/code/9794.html" target="_blank">Map</a><String,String> map = Sign.sign(jsapi_ticket, "http://www.vxzsk.com/weChat/wxJsAPIServlet");

String timestamp = map.get("timestamp");

String nonceStr = map.get("nonceStr");

String signature = map.get("signature");

String appId = "你自己的应用id";

request.setAttribute("appId", appId);

request.setAttribute("timestamp", timestamp);

request.setAttribute("signature",signature);

request.setAttribute("nonceStr", nonceStr);

request.getRequestDispatcher("jsapi/jsapi.jsp").forward(request, response);

}

注意用户点击的地址必须和签名算法中的地址保持一致,如果要带参数那么参数也要带上而且参数的顺序不能改变,否则签名算法得到的签名 字符串和用户请求的地址的签名字符串不一致导致调用jsapi失败。

当然我在这里用的servlet跳转,读者也可以把doGET方法中的代码复制到spring的一个普通controller中或者struts中的一个普通的action方法中。

Sign.java代码

package com.test.util;
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;  
  public class Sign {
    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        //注意这里参数名必须全部小写,且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
        System.out.println(string1);
        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        return ret;
    }
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }
    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
    public static void main(String[] args) {
        String jsapi_ticket =JsapiTicketUtil.getJSApiTicket();
        // 注意 URL 一定要动态获取,不能 hardcode
        String url = "http://www.vxzsk.com/xx/x.do";//url是你请求的一个action或者controller地址,并且方法直接跳转到使用jsapi的jsp界面
        Map<String, String> ret = sign(jsapi_ticket, url);
        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }
    };
}
Copy after login


JsapiTicketUtil.java代码

package com.test.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import net.sf.json.JSONObject;
import com.test.weixin.TestAcessToken;
public class JsapiTicketUtil {
    /***
     * 模拟get请求
     * @param url
     * @param charset
     * @param timeout
     * @return
     */
     public static String sendGet(String url, String charset, int timeout)
      {
        String result = "";
        try
        {
          URL u = new URL(url);
          try
          {
            URLConnection conn = u.openConnection();
            conn.connect();
            conn.setConnectTimeout(timeout);
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
            String line="";
            while ((line = in.readLine()) != null)
            {
              result = result + line;
            }
            in.close();
          } catch (IOException e) {
            return result;
          }
        }
        catch (MalformedURLException e)
        {
          return result;
        }
        return result;
      }
     public static String getAccessToken(){
            String appid="你公众号基本设置里的应用id";//应用ID
            String appSecret="你公众号基本设置里的应用密钥";//(应用密钥)
            String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appSecret+"";
            String backData=TestAcessToken.sendGet(url, "utf-8", 10000);
            String accessToken = (String) JSONObject.fromObject(backData).get("access_token");  
            return accessToken;
     }
    public static String getJSApiTicket(){ 
        //获取token
        String acess_token= JsapiTicketUtil.getAccessToken();
        String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+acess_token+"&type=jsapi";  
        String backData=TestAcessToken.sendGet(urlStr, "utf-8", 10000);  
        String ticket = (String) JSONObject.fromObject(backData).get("ticket");  
        return  ticket;  
    }  
    public static void main(String[] args) {
        String jsapiTicket = JsapiTicketUtil.getJSApiTicket();
        System.out.println("调用微信jsapi的凭证票为:"+jsapiTicket);
    }
}
Copy after login


Third, the renderings are as follows

WeChat development method to determine whether the current client supports the specified js interface

##The "WeChat jsapi test interface" in the picture is connected to the link address in the signature algorithm

WeChat development method to determine whether the current client supports the specified js interface

##

The above is the detailed content of WeChat development method to determine whether the current client supports the specified js interface. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template