Detailed explanation of the preliminary access method of WeChat jsapi and java developed by WeChat

高洛峰
Release: 2017-03-26 14:08:42
Original
2251 people have browsed it

Parameter name

http://www.php.cn/wiki/835.html" target="_blank">width="346" valign= "top" style="word-break:break-all"> Description
appId App ID Log in to the WeChat public account management platform CanQuery
timestamp Required, generate a signed timestamp
nonceStr Required, random string to generate signature
signature Required, signature, see Appendix 1

The parameters in the above table have been explained very clearly in the previous chapter. The reason why we make a table is because if we want to successfully access WeChatjsapiThese four parameters are credentials, which is equivalent to a door that must have four keys to open. One of them is indispensable. .

The following case uses the jump page made by java's servlet. SpringMVC is not used. You can change the requested path to the controller path. .

WxJsAPIServlet code:

package com.test;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Map;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.test.util.JsapiTicketUtil;

import com.test.util.Sign;

public class WxJsAPIServlet extends HttpServlet {

/**

     * Constructor of the object.

     */

    public WxJsAPIServlet() {

        super();

    }

/**

     * Destruction of the servlet. 

     */

    public void destroy() {

        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }

    /**

     * The doGet method of the servlet. 

     *

     * This method is called when a form has its tag value method equals to get.

     * 

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

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

        String jsapi_ticket =JsapiTicketUtil.getJSApiTicket();;

        Map 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);

    }

    /**

     * The doPost method of the servlet. 

     *

* This method is called when a form has its tag value method equals to post.

*

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

* /

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

this.doGet(request, response);

}

/**

     * Initialization of the servlet. 

     *

     * @throws ServletException if an error occurs

     */

public void init() throws ServletException {

// Put your code here

}

}

Line 44 is the tool class that generates jsapi_ticket. The code for the tool class is posted below.

Line 45 The sign method of the Sign class encapsulates the last three parameters in the table into the Map collection. The parameter is the requested servlet address and jumps to the jsp interface that calls WeChat jsapi.

Line 49 replace appId with your own application id, if you don’t know the application id You can log in to the WeChat public platform management center to check.

Servlet corresponding web.xmlCode

## Generate Signature algorithm class Sign code:
##

This is the description of my J2EE component

display-name>This is the display name of my J2EE component WxJsAPIServlet

;/servlet-class>

WxJsAPIServlet

/wxJsAPIServlet

package com.test.util;

/***

* V-shaped knowledge base www.vxzsk.com

*/

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 sign(String jsapi_ticket, String url) {

        Map ret = new HashMap();

        String nonce_str = create_nonce_str();

        String timestamp = create_timestamp();

        String string1;

        String signature = "";

        //注意这里参数名必须全部小写,且必须有序

        string1 = "jsapi_ticket=" + jsapi_ticket +

                  "&noncestr=" + nonce_str +

                  "×tamp=" + 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;

##}

_nonce_str () () {

Return uuid.randomuuid (). Tostring ();

##}

##Qate Static Stration Create_timestAmp () {

Retostring (System.currentTimeMillis() / 1000);

}

public static void

main

(String[] args) {

String jsapi_ticket =JsapiTicketUtil .getJSApiTicket();

                                                 ’’’’’ ’s . /url is an

action

or controller address you requested, and the method jumps directly to the jsp interface using jsapi

Map ret = sign(jsapi_ticket, url);

for (Map.Entry entry : ret.entrySet()) {

System.out.println(entry.getKey() + ", " + entry.getValue());

                                                                                                                                                      

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 {

    /***

* Simulate get request

* @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(){ 

//Get 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("The ticket for calling WeChat jsapi is: "+jsapiTicket);

}

}

There is a method to obtain access_token in the above code, please change your own parameters

jsapi.jsp code

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  head>

    ">

    

微信jsapi测试-V型知识库

    viewport" content="width=320.1,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">

   <script> </script> 

  

  

  

欢迎来到微信jsapi测试界面-V型知识库

  

     

timestamp:${ timestamp}

  

     

nonceStr:${ nonceStr}

  

     

signature:${ signature}

  

     

appId:${ appId}

  

    onclick="uploadImg();"/>  

    获取当前位置" onclick="getLocation();"/>  

  

  

  wx.config({  

    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。  

    appId: '${appId}', // 必填,公众号的唯一标识  

    timestamp: '${ timestamp}' , // 必填,生成签名的时间戳  

    nonceStr: '${ nonceStr}', // 必填,生成签名的随机串  

    signature: '${ signature}',// 必填,签名,见附录1  

    jsApiList: ['chooseImage','getLocation','openLocation'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2  

});  

wx.ready(function(){  

    alert("ready");  

});  

wx.error(function (res) {

  alert("调用微信jsapi返回的状态:"+res.errMsg);

});

function uploadImg() {  

    wx.checkJsApi({  

        jsApiList: ['chooseImage','openLocation','getLocation'], // 需要检测的JS接口列表,所有JS接口列表见附录2,  

        success: function(res) {  

            // 以键值对的形式返回,可用的api值true,不可用为false  

                                                                                                                                                                                               ({

          

count

: 1, // Default 9                                                                                                                                                                                          , the default is both

            sourceType: ['album', 'camera'], // You can specify whether the source is the album or the camera, the default is both                                                                                   ) {

var localIds = res.localIds; // Return the local ID list of the selected photo, localId can be displayed as the src

attribute

of the

img tag

Picture

alert(localIds); }); }

function getLocation() {

var latitude = "";

var longitude = "";

wx.getLocation({

type: 'gcj02', // The default is the gps coordinates of wgs84. If you want to return the Mars coordinates directly for openLocation, you can pass in 'gcj02'

success: function (res) {

# Latitude = res.Latitude; // Staintable, floating point number, range of 90 ~ -90

# Longitude = res.longitude; // longitude, floating point number, range of 180 ~- 180.

var speed = res.speed; // Speed, in meters per second

var accuracy = res.accuracy; // Position accuracy

wx.openLocation( {

            latitude: latitude, // Latitude, floating point number, range is 90 ~ -90

                                                                                                                                                            

# name: 'Your current location', // Location name

address: 'currentLocation', // Address details

Scale: 26, //

Map

Zoom level, shaping value, ranging from 1 to 28. The default is maximum

.

Infourl: '' // View the hyperlinks at the bottom of the position interface , you can click to jump

});

##}

# });

}

The above is the detailed content of Detailed explanation of the preliminary access method of WeChat jsapi and java developed by WeChat. 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