微信公众号之分享接口服务器端
前言
Github:https://github.com/HealerJean
我们会发现一些微信公众号中的网站,他们有的分享出去标题以及摘要是自定义的,那么这就是用到了分享接口
1、h5需要的数据实体类
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.Date;
/**
* 作者 :HealerJean
* 日期 :2018/12/17 下午7:11.
* 类描述:
*/
@Data
@Accessors
public class ResJsApiTickeData {
private String appId ; //微信公众号id
private Long timestamp ;//时间戳
private String nonceStr; //随机字符串
private String signature ; //签名
}
2、获取JSapi中的ticket
/**
* @Desc: JsapiTicket
* @Date: 2018/5/24 下午6:50
*/
public static String getJsapiTicket( WeChatBusinessNo weChatBusinessNo){
WeChatJsApiTicket weChatJsApiTicket =jsSdkUtils.getWechatJsapiTicket(weChatBusinessNo.getId());
if(weChatJsApiTicket !=null){ //先判断数据库中有没有
return weChatJsApiTicket.getJsTicke();
}
String accessToken = AccessToakeUtil.getAccessToaken(weChatBusinessNo);
String url = WechatApiUrlParams.JS_API_TICKET_URL.replace("ACCESS_TOKEN", accessToken) ;
HttpBackBean httpBackBean = HttpHelper.handleGet(url,null,null, HttpHelper.OVERTIME);
log.info("获取 accessToken 返回结果"+httpBackBean.getResult());
String jsTicket = JSONObject.fromObject(httpBackBean.getResult()).getString("ticket");
if(jsTicket!=null){
jsSdkUtils.saveWechatJsapiTicket(jsTicket, weChatBusinessNo.getId()); //向数据库中保存accessToaken
return jsTicket;
}else {
log.error("获取accessToken失败");
}
return null;
}
3、根据前台传来的url制作签名
public ResJsApiTickeData getSignature(String url, String key){
ResJsApiTickeData data = new ResJsApiTickeData() ;
WechatWebKey wechatWebKey = wechatWebKeyRepository.findByWeChatWebKey(key);
WeChatBusinessNo fuweChatBusinessNo = weChatBusinessNoRepository.findOne(wechatWebKey.getFuId());
data.setAppId(fuweChatBusinessNo.getAppId());
Long timestamp = System.currentTimeMillis() ;
data.setTimestamp(timestamp);
String noncestr = StringGeneratorUtil.generateString(5);
data.setNonceStr(noncestr);
String jsTicket= JsSdkUtils.getJsapiTicket(fuweChatBusinessNo);
data.setSignature(JsSdkUtils.sign(jsTicket, url, noncestr, timestamp));
return data ;
}
4、签名制作
/**
*
* 作者: HealerJean
* 日期: 2018/12/11 下午5:14.
* 方法描述: 开始JS——SDK签名
*/
public static String sign(String jsapi_ticket, String url,String noncestr ,Long timestamp) {
//注意这里参数名必须全部小写,且必须有序
String str = "jsapi_ticket=" + jsapi_ticket +
"&noncestr=" + noncestr +
"×tamp=" + timestamp +
"&url=" + url;
String signature = AesUtils.SHA1(str);
return signature;
}
/**
* 微信 校验 SHA1 加密
*
* @param decript
* @return
*/
public static String SHA1(String decript) {
try {
MessageDigest digest = 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 "";
}