微信JSSDK自定义分享Java版

微信JSSDK自定义分享Java版

从百度上找寻了大量的资料,发现都比较模糊,还有很多PHP版本的,特此写一个Java版本的,比较简单的版本。


步骤一:公众号设置

首先要有个认证的订阅号或者服务号,如果没有,那你可以×掉网页了。在公众号中需要设置:JS安全域名->下载验证txt到服务器根目录验证->知道自己公众号的AppId和AppSecret->设置IP白名单。参考具体操作:自定义微信分享 凡科。友情提示:IP白名单至少两个,一个是服务器IP,一个是当前开发电脑的公网IP。


步骤二:后台代码的搭建

核心步骤为:获取AccessToken->通过AccessToken获取Ticket->通过Ticket和浏览器url进行签名->返回数据到前端

搞懂之后很简单,只需要看懂一点点代码就行,主要核心代码微信已经提供好了。当前项目时用spring mvc作为控制层,后台只有三个文件HttpRequestUtil.javaSign.javaController.java

第一个java文件是Java Http请求的方法,第二个是微信官方提供的签名方法,第三个是自己手动写的Controller层。

下面我将会一一贴出来。


Controller.java:

mport com.txbsl.Utils.HttpRequestUtil;
import com.txbsl.Utils.Sign;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Controller
{
  public static final String AppI = "*******************";
  public static final String AppS = "********************************";
  public static final String AccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+AppI+"&secret="+AppS;
  public static final String TicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
  public static String AccessToken = null;
  public static String Ticket = null;
  
  @ResponseBody
  @RequestMapping({"/getMsg"})
  public Map test(HttpServletRequest request, String url)
    throws Exception
  {
    JSONObject jsonObject = HttpRequestUtil.httpRequest(AccessTokenUrl, "GET", "");
    AccessToken = (String)jsonObject.get("access_token");
    String requestUrl = TicketUrl.replace("ACCESS_TOKEN", AccessToken);
    JSONObject jsonObject2 = HttpRequestUtil.httpRequest(requestUrl, "GET", "");
    Ticket = (String)jsonObject2.get("ticket");
    Map map = Sign.sign(Ticket, url);
    return map;
  }
}

HttpRequestUtil.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;

public class HttpRequestUtil
{
  public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)
  {
    JSONObject jsonObject = null;
    StringBuffer buffer = new StringBuffer();
    InputStream inputStream = null;
    try
    {
      URL url = new URL(requestUrl);
      HttpURLConnection httpUrlConn = (HttpURLConnection)url.openConnection();
      httpUrlConn.setDoOutput(true);
      httpUrlConn.setDoInput(true);
      httpUrlConn.setUseCaches(false);
      
      httpUrlConn.setRequestMethod(requestMethod);
      if ("GET".equalsIgnoreCase(requestMethod)) {
        httpUrlConn.connect();
      }
      if (null != outputStr)
      {
        OutputStream outputStream = httpUrlConn.getOutputStream();
        
        outputStream.write(outputStr.getBytes("UTF-8"));
        outputStream.close();
      }
      inputStream = httpUrlConn.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      
      String str = null;
      while ((str = bufferedReader.readLine()) != null) {
        buffer.append(str);
      }
      bufferedReader.close();
      inputStreamReader.close();
      
      inputStream.close();
      inputStream = null;
      httpUrlConn.disconnect();
      
      return JSONObject.fromObject(buffer.toString());
    }
    catch (ConnectException ce)
    {
      ce.printStackTrace();
      System.out.println("Weixin server connection timed out");
    }
    catch (Exception e)
    {
      e.printStackTrace();
      System.out.println("http request error:{}");
    }
    finally
    {
      try
      {
        if (inputStream != null) {
          inputStream.close();
        }
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
  }
}

Sign.java


import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

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 signature = "";
    

    String 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(byte[] hash)
  {
    Formatter formatter = new Formatter();
    for (byte b : hash) {
      formatter.format("%02x", new Object[] { Byte.valueOf(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() / 1000L);
  }
}

步骤三:前端页面配置

主要就是添加weixin.js , jquery.js ,再自己写一段js,核心代码如下:







你可能感兴趣的:(微信)