Table of Contents
欢迎来到微信jsapi测试界面-V型知识库
Home WeChat Applet WeChat Development WeChat development method to determine whether the current client supports the specified js interface

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

Mar 26, 2017 pm 02:55 PM
WeChat development

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 id="欢迎来到微信jsapi测试界面-V型知识库">欢迎来到微信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!

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

PHP WeChat development: How to implement message encryption and decryption PHP WeChat development: How to implement message encryption and decryption May 13, 2023 am 11:40 AM

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

Using PHP to develop WeChat mass messaging tools Using PHP to develop WeChat mass messaging tools May 13, 2023 pm 05:00 PM

With the popularity of WeChat, more and more companies are beginning to use it as a marketing tool. The WeChat group messaging function is one of the important means for enterprises to conduct WeChat marketing. However, if you only rely on manual sending, it is an extremely time-consuming and laborious task for marketers. Therefore, it is particularly important to develop a WeChat mass messaging tool. This article will introduce how to use PHP to develop WeChat mass messaging tools. 1. Preparation work To develop WeChat mass messaging tools, we need to master the following technical points: Basic knowledge of PHP WeChat public platform development Development tools: Sub

PHP WeChat development: How to implement user tag management PHP WeChat development: How to implement user tag management May 13, 2023 pm 04:31 PM

In the development of WeChat public accounts, user tag management is a very important function, which allows developers to better understand and manage their users. This article will introduce how to use PHP to implement the WeChat user tag management function. 1. Obtain the openid of the WeChat user. Before using the WeChat user tag management function, we first need to obtain the user's openid. In the development of WeChat public accounts, it is a common practice to obtain openid through user authorization. After the user authorization is completed, we can obtain the user through the following code

PHP WeChat development: How to implement group message sending records PHP WeChat development: How to implement group message sending records May 13, 2023 pm 04:31 PM

As WeChat becomes an increasingly important communication tool in people's lives, its agile messaging function is quickly favored by a large number of enterprises and individuals. For enterprises, developing WeChat into a marketing platform has become a trend, and the importance of WeChat development has gradually become more prominent. Among them, the group sending function is even more widely used. So, as a PHP programmer, how to implement group message sending records? The following will give you a brief introduction. 1. Understand the development knowledge related to WeChat public accounts. Before understanding how to implement group message sending records, I

Steps to implement WeChat public account development using PHP Steps to implement WeChat public account development using PHP Jun 27, 2023 pm 12:26 PM

How to use PHP to develop WeChat public accounts WeChat public accounts have become an important channel for promotion and interaction for many companies, and PHP, as a commonly used Web language, can also be used to develop WeChat public accounts. This article will introduce the specific steps to use PHP to develop WeChat public accounts. Step 1: Obtain the developer account of the WeChat official account. Before starting the development of the WeChat official account, you need to apply for a developer account of the WeChat official account. For the specific registration process, please refer to the official website of WeChat public platform

PHP WeChat development: How to implement voting function PHP WeChat development: How to implement voting function May 14, 2023 am 11:21 AM

In the development of WeChat public accounts, the voting function is often used. The voting function is a great way for users to quickly participate in interactions, and it is also an important tool for holding events and surveying opinions. This article will introduce you how to use PHP to implement WeChat voting function. Obtain the authorization of the WeChat official account. First, you need to obtain the authorization of the WeChat official account. On the WeChat public platform, you need to configure the API address of the WeChat public account, the official account, and the token corresponding to the public account. In the process of our development using PHP language, we need to use the PH officially provided by WeChat

PHP WeChat development: How to implement customer service chat window management PHP WeChat development: How to implement customer service chat window management May 13, 2023 pm 05:51 PM

WeChat is currently one of the social platforms with the largest user base in the world. With the popularity of mobile Internet, more and more companies are beginning to realize the importance of WeChat marketing. When conducting WeChat marketing, customer service is a crucial part. In order to better manage the customer service chat window, we can use PHP language for WeChat development. 1. Introduction to PHP WeChat development PHP is an open source server-side scripting language that is widely used in the field of Web development. Combined with the development interface provided by WeChat public platform, we can use PHP language to conduct WeChat

How to use PHP for WeChat development? How to use PHP for WeChat development? May 21, 2023 am 08:37 AM

With the development of the Internet and mobile smart devices, WeChat has become an indispensable part of the social and marketing fields. In this increasingly digital era, how to use PHP for WeChat development has become the focus of many developers. This article mainly introduces the relevant knowledge points on how to use PHP for WeChat development, as well as some of the tips and precautions. 1. Development environment preparation Before developing WeChat, you first need to prepare the corresponding development environment. Specifically, you need to install the PHP operating environment and the WeChat public platform

See all articles