search
HomeWeChat AppletWeChat DevelopmentJava for WeChat development to obtain WeChat timestamp, nonceStr, signature method

According to WeChat’s official documents and case code, the above three parameters are necessary, and the above three parameters are obtained dynamically. Then, next, we use java code to achieve the acquisition according to WeChat’s official documents. The three parameters of timestamp, nonceStr, and signature are just a main method here to print and output. This lesson does not implement passing these three parameters to the web page and successfully calling up the WeChat jsapi. The next lesson will focus on the explanation. .

##Sign code:

##
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 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());
        }
    };
  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);
    }
}

The variable url in the main method on line 16 is the one you requested action or controller address, and the method jumps directly to the jsp interface using jsapi

Get the jsapi_ticket tool class code:

Readers can directly copy the code to myeclipse or Eclipse and run the main method, but here we remind readers to obtain it from
#
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;
/***
 * @author V型知识库  www.vxzsk.com
 *
 */
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);
 
    }
 
}



JsapiTicketUtil In the acces_token method, readers need to fill in their own appid and appsecret.

The above is the detailed content of Java for WeChat development to obtain WeChat timestamp, nonceStr, signature method. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
PHP微信开发:如何实现消息加密解密PHP微信开发:如何实现消息加密解密May 13, 2023 am 11:40 AM

PHP是一种开源的脚本语言,广泛应用于Web开发和服务器端编程,尤其在微信开发中得到了广泛的应用。如今,越来越多的企业和开发者开始使用PHP进行微信开发,因为它成为了一款真正的易学易用的开发语言。在微信开发中,消息的加密和解密是一个非常重要的问题,因为它们涉及到数据的安全性。对于没有加密和解密方式的消息,黑客可以轻松获取到其中的数据,对用户造成威胁

PHP微信开发:如何实现客服聊天窗口管理PHP微信开发:如何实现客服聊天窗口管理May 13, 2023 pm 05:51 PM

微信是目前全球用户规模最大的社交平台之一,随着移动互联网的普及,越来越多的企业开始意识到微信营销的重要性。在进行微信营销时,客服服务是至关重要的一环。为了更好地管理客服聊天窗口,我们可以借助PHP语言进行微信开发。一、PHP微信开发简介PHP是一种开源的服务器端脚本语言,广泛运用于Web开发领域。结合微信公众平台提供的开发接口,我们可以使用PHP语言进行微信

PHP微信开发:如何实现用户标签管理PHP微信开发:如何实现用户标签管理May 13, 2023 pm 04:31 PM

在微信公众号开发中,用户标签管理是一个非常重要的功能,可以让开发者更好地了解和管理自己的用户。本篇文章将介绍如何使用PHP实现微信用户标签管理功能。一、获取微信用户openid在使用微信用户标签管理功能之前,我们首先需要获取用户的openid。在微信公众号开发中,通过用户授权的方式获取openid是比较常见的做法。在用户授权完成后,我们可以通过以下代码获取用

用PHP开发微信群发工具用PHP开发微信群发工具May 13, 2023 pm 05:00 PM

随着微信的普及,越来越多的企业开始将其作为营销工具。而微信群发功能,则是企业进行微信营销的重要手段之一。但是,如果只依靠手动发送,对于营销人员来说是一件极为费时费力的工作。所以,开发一款微信群发工具就显得尤为重要。本文将介绍如何使用PHP开发微信群发工具。一、准备工作开发微信群发工具,我们需要掌握以下几个技术点:PHP基础知识微信公众平台开发开发工具:Sub

如何使用PHP进行微信开发?如何使用PHP进行微信开发?May 21, 2023 am 08:37 AM

随着互联网和移动智能设备的发展,微信成为了社交和营销领域不可或缺的一部分。在这个越来越数字化的时代,如何使用PHP进行微信开发已经成为了很多开发者的关注点。本文主要介绍如何使用PHP进行微信开发的相关知识点,以及其中的一些技巧和注意事项。一、开发环境准备在进行微信开发之前,首先需要准备好相应的开发环境。具体来说,需要安装PHP的运行环境,以及微信公众平台提

PHP微信开发:如何实现群发消息发送记录PHP微信开发:如何实现群发消息发送记录May 13, 2023 pm 04:31 PM

随着微信成为了人们生活中越来越重要的一个通讯工具,其敏捷的消息传递功能迅速受到广大企业和个人的青睐。对于企业而言,将微信发展为一个营销平台已经成为趋势,而微信开发的重要性也逐渐凸显。在其中,群发功能更是被广泛使用,那么,作为PHP程序员,如何实现群发消息发送记录呢?下面将为大家简单介绍一下。1.了解微信公众号相关开发知识在了解如何实现群发消息发送记录之前,我

ThinkPHP6微信开发指南:快速搭建微信公众号应用ThinkPHP6微信开发指南:快速搭建微信公众号应用Aug 26, 2023 pm 11:55 PM

ThinkPHP6微信开发指南:快速搭建微信公众号应用引言:微信公众号作为一种重要的社交媒体平台,为个人和企业在市场推广、信息传播等方面提供了很大的机会。在这篇文章中,我们将介绍如何使用ThinkPHP6快速搭建一个微信公众号应用,并且提供一些常用的代码示例。环境准备在开始开发之前,我们首先需要准备好以下环境:PHP7以上版本ThinkPHP6框架微信公众号

PHP微信开发:如何实现语音识别PHP微信开发:如何实现语音识别May 13, 2023 pm 09:31 PM

随着移动互联网的普及,微信作为一款社交软件,越来越多的人开始使用,并且微信开放平台也给开发者带来了众多的机会。近年来,随着人工智能技术的发展,语音识别技术逐渐成为了移动端开发的热门技术之一。在微信开发中,如何实现语音识别成为很多开发者关注的问题。本文将介绍如何利用PHP开发微信应用实现语音识别功能。一、语音识别原理在介绍如何实现语音识别之前,我们先了解一下语

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment