步骤一:绑定域名
先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
备注:登录后可在“开发者中心”查看对应的接口权限。
点击设置js安全域名域名,下载此文件到项目根目录,并设置一个外网域名.下载好以后启动项目,与安全域名对接.点击确认设置成功
项目中如下
1:appid 下图获得
2:timestamp 时间戳
timestamp= Long.toString(System.currentTimeMillis() / 1000);
3:nonceStr 随机串
nonceStr=UUID.randomUUID().toString();
4:signature 签名
//获取access_token
String APPID=XXX;
String APPSECRET=XXX;
String tokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;
AccessTokenDTO accessTokenDTO=new Gson().fromJson(tokenUrl,AcessTokenDTO.class);
String ACCESS_TOKEN =accessTokenDTO.getAccessToken();
String jsapiUrl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ACCESS_TOKEN+"&type=jsapi";
//获取ticket
String ticketJson="";
ticketJson=HttpClientUtil.doGet(jsapiUrl);
TicketDTO ticketDTO=new Gson().fromJson(ticketJson,TicketDTO.class);
String ticket="";
ticket=ticketDTO.getTicket();
HttpClientUtil源码:
package XXX.XXXX.XX; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpClientUtil { public static String doGet(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGet(String url) { return doGet(url, null); } public static String doPost(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List<NameValuePair> paramList =new ArrayList<NameValuePair>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doPost(String url) { return doPost(url, null); } public static String doPostJson(String url, String json) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doPostJson(String url, String json, Integer timeOut) { // 创建Httpclient对象 RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(timeOut) .setConnectionRequestTimeout(timeOut) .setSocketTimeout(timeOut) .build(); CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doPost(String url, Map<String, String> param, Integer timeOut) { // 创建Httpclient对象 RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(timeOut) .setConnectionRequestTimeout(timeOut) .setSocketTimeout(timeOut) .build(); CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List<NameValuePair> paramList =new ArrayList<NameValuePair>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } /** * 根据地址获得数据的字节流 * @param strUrl 网络连接地址 * @return */ public static byte[] getImageFromNetByUrl(String strUrl){ try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream();//通过输入流获取图片数据 byte[] btImg = readInputStream(inStream);//得到图片的二进制数据 return btImg; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 从输入流中获取数据 * @param inStream 输入流 * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len=inStream.read(buffer)) != -1 ){ outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); } private static String TruncateUrlPage(String strURL) { String strAllParam = null; String[] arrSplit = null; strURL = strURL.trim().toLowerCase(); arrSplit = strURL.split("[?]"); if (strURL.length() > 1) { if (arrSplit.length > 1) { if (arrSplit[1] != null) { strAllParam = arrSplit[1]; } } } return strAllParam; } /** * * <p>Title: URLRequest</p> * <p>Description: 提取URL中的值</p> * @param URL * @return */ public static Map<String, String> urlRequest(String URL) { Map<String, String> mapRequest = new HashMap<String, String>(); String[] arrSplit = null; String strUrlParam = TruncateUrlPage(URL); if (strUrlParam == null) { return mapRequest; } // 每个键值为一组 www.2cto.com arrSplit = strUrlParam.split("[&]"); for (String strSplit : arrSplit) { String[] arrSplitEqual = null; arrSplitEqual = strSplit.split("[=]"); // 解析出键值 if (arrSplitEqual.length > 1) { // 正确解析 mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]); } else { if (arrSplitEqual[0] != "") { // 只有参数没有值,不加入 mapRequest.put(arrSplitEqual[0], ""); } } } return mapRequest; } /** * 发送HttpPost请求 * * @param strURL * 服务地址 * @param params * json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/> * @return 成功:返回json字符串<br/> */ public static String post(String strURL, String params) { System.out.println(strURL); System.out.println(params); try { URL url = new URL(strURL);// 创建连接 HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); // 设置请求方式 connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式 connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式 connection.connect(); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码 out.append(params); out.flush(); out.close(); // 读取响应 int length = (int) connection.getContentLength();// 获取长度 InputStream is = connection.getInputStream(); if (length != -1) { byte[] data = new byte[length]; byte[] temp = new byte[512]; int readLen = 0; int destPos = 0; while ((readLen = is.read(temp)) > 0) { System.arraycopy(temp, 0, data, destPos, readLen); destPos += readLen; } String result = new String(data, "UTF-8"); // utf-8编码 System.out.println(result); return result; } } catch (IOException e) { e.printStackTrace(); } return "error"; // 自定义错误信息 } }
Gson pom依赖:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency>
TicketDTO:
package xxx.xxx.xx.xx import com.fasterxml.jackson.annotation.JsonProperty; /** * 临时票据Ticket 数据封装类 * @author xxx * @data 2018/5/29 */ public class TicketDTO { private String errcode; private String errmsg; private String ticket; /** * 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称 */ @JsonProperty("expires_in") private String expiresIn; public String getErrcode() { return errcode; } public void setErrcode(String errcode) { this.errcode = errcode; } public String getErrmsg() { return errmsg; } public void setErrmsg(String errmsg) { this.errmsg = errmsg; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getExpiresIn() { return expiresIn; } public void setExpiresIn(String expiresIn) { this.expiresIn = expiresIn; } @Override public String toString() { return "TicketDTO{" + "errcode='" + errcode + '\'' + ", errmsg='" + errmsg + '\'' + ", ticket='" + ticket + '\'' + ", expiresIn='" + expiresIn + '\'' + '}'; } }
@JsonProperty pom依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
String url =跳转分享的域名:自定义
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(Exception ex){}
将数据传递给前端js:wx.config接收;
1.1.4 步骤四:通过ready接口处理成功验证:wx.config验证成功以后触发事件动作
wx.ready(function(){
//放入要分享的事件
});
例如:
1.1.5 步骤五:通过error接口处理失败验证wx.config验证失败以后触发事件动作
3.1 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口(即将废弃)
3.2 获取“分享给朋友”按钮点击状态及自定义分享内容接口(即将废弃)
3.4 获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
3.5 获取“分享到QQ空间”按钮点击状态及自定义分享内容接口