1.登陆【微信公众号平台】,打开【设置】>>>【微信认证】检查当前公众号是否认证,如果没有,需要先进行微信认证。
2..打开【微信公众号平台】中的【基本配置】,将服务器的IP添加到【公众号开发信息】的【IP白名单】中
3.打开【微信公众号平台】中的【公众号设置】里面的【功能设置】,分别在【业务域名】和【JS接口安全域名】两项中填写当 前项目的二级域名(听说好像必须是二级域名,而且必须是备案过的),配置域名时****.txt这个文件存放的路径为服务器tomcat所映射的项目文件夹,比如:
那么,你就需要把这个****.txt文件放在这里
如果放的位置正确,那么填完域名确定的时候是会验证通过的。
4.设置完以上地方,现在就该使用微信的JSSDK进行分享页标题,概述,缩略图的自定义了
首先,在要分享的html中添加引用
<script type="text/javascript" src="https://res2.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
然后
<script>
$(function () {
$.ajax({
url: 'getWxConfig',
type: 'POST',
dataType: 'json',
data: {"url": encodeURIComponent(window.location.href.split("#")[0])}
}).done(function (res) {
console.log(res)
wx.config({
debug: ture, //调试阶段建议开启,在线上时需要改为false
appId: res.appId,//APPID
timestamp: res.timestamp,//调用方法拿到的时间戳timestamp
nonceStr: res.nonceStr,//调用方法拿到的随机数nonceStr
signature: res.signature,//调用方法拿到的签名signature
//需要调用的方法接口
jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareWeibo', 'onMenuShareQQ', 'onMenuShareQZone']
});
})
wx.ready(function () {
wx.onMenuShareTimeline({
title: "", // 分享标题
link: window.location.href, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: "", // 分享页的缩略图(绝对路径/在线引用路径)
success: function () {
// alert("成功")
// 用户点击了分享后执行的回调函数
alert("分享成功!!!");
}
});
wx.onMenuShareAppMessage({
title: "", // 分享标题
desc: "", // 分享描述
link: window.location.href, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: "", // 分享页的缩略图(绝对路径/在线引用路径)
type: '', // 分享类型,music、video或link,不填默认为link
dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
success: function () {
// 用户点击了分享后执行的回调函数
alert("分享成功!!!");
}
});
});
})
</script>
然后后台编写一个名为WxController的controller
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* 微信分享
*
* @author cd
* @date 2019-8-16
*/
@Controller
public class WxController {
/**
* 获取Access_token
*
* @param appId 公众号appId
* @param appSecret 公众号密钥
* @return
*/
public static String getAccess_token(String appId, String appSecret) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
String accessToken = null;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
// 必须是get方式请求
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
// 连接超时30秒
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
// 读取超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject jsonObj = JSONObject.fromObject(message);
accessToken = jsonObj.getString("access_token");
} catch (Exception e) {
e.printStackTrace();
}
return accessToken;
}
/**
* 获得ACCESS_TICKET
*
* @param access_token
* @return
*/
public static String getAccess_ticket(String access_token) {
String ticket = null;
//这个url链接和参数不能变
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
// 必须是get方式请求
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
// 连接超时30秒
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
// 读取超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.fromObject(message);
System.out.println("JSON字符串:" + demoJson);
ticket = demoJson.getString("ticket");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return ticket;
}
/**
* 将字符串进行sha1加密
*
* @param decript
* @return
*/
public static String SHA1(String decript) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// 字节数组转换为 十六进制 数
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
/**
* 页面中wx.config所要调用的接口
*
* @param request
* @param response
*/
@RequestMapping("getWxConfig")
@ResponseBody
public void doPost(HttpServletRequest request, HttpServletResponse response) {
//appId和appSecret
String appId = "公众号appid";
String appSecret = "公众号密钥";
//外部传入url获取url url需要是微信中打开的url否则会报错。
String URL = request.getParameter("url");
//转换url
String url = "";
//需要转换解码url
try {
url = java.net.URLDecoder.decode(URL, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//获取access_token
String aeecss_token = getAccess_token(appId, appSecret);
//获取access_ticket
String aeecss_ticket = getAccess_ticket(aeecss_token);
//3、时间戳和随机字符串
String nonceStr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
//4、获取url,将参数排序并拼接字符串
String str = "jsapi_ticket=" + aeecss_ticket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url;
//6、将字符串进行sha1加密
String signature = SHA1(str);
Map<String, String> map = new HashMap();
map.put("appId", appId);
map.put("timestamp", timestamp);
map.put("accessToken", aeecss_token);
map.put("ticket", aeecss_ticket);
map.put("nonceStr", nonceStr);
map.put("signature", signature);
JSONObject jsonObject = JSONObject.fromObject(map);
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter pw = null;
try {
pw = response.getWriter();
} catch (IOException e1) {
e1.printStackTrace();
}
pw.write(jsonObject.toString());
pw.close();
}
}
最后,在微信中打开要分享的页面,点击右上角>>【发送给朋友】,就可以看到效果啦(需要在线上测试)