首先提供一个微信官方地址点击打开链接
早期web项目中经常用到微信分享功能,现在整理一下,供记忆与分享,开发环境为JAVA +H5。
1、微信的开发环境不在多说,大概为:使用已备案的域名,设置“公众号设置”的三项域名、
设置开发者密码(AppSecret)、调试通过核心服务地址。
2、公众平台以access_token为接口调用凭据,来调用接口,所有接口的调用需要先获取access_token,access_token在2小时内有效,过期需要重新获取,但1天内获取次数有限,开发者需自行存储。在线测试地址点击打开链接
接口地址:JSAPI_Access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
提供必要参数: String tokenURL=JSAPI_Access_token+"&appid="+appid+"&secret="+secret;3、用第一步拿到的access_token 采用http GET方式请求获得jsapi_ticket(有效期7200秒,开发者必须在自己的服务全局缓存jsapi_ticket);
String JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi";
以上JS-SDK接口是基础,比较简单,注意细节即可。
4、签名计算
public static Map sign(String jsapi_ticket, String url) {
Map ret = new HashMap();
String nonce_str = echostr();
String timestamp = getTimeStamp();
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;
}
5、WEB前端js函数封装,页面加载是注册分享事件
function wxSharecfg(response, setFx) {
var Request = new Object();
Request = GetRequest();
var d = Request["demo"];
wx.config({
debug: false,
appId: response.appId,
timestamp: response.timestamp,
nonceStr: response.nonceStr,
signature: response.signature,
jsApiList: [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'onMenuShareQZone'
]
});
wx.ready(function () {
var shareData = {
imgUrl: urlStr ,//图片地址
link: url,
title: "标题",
desc: setFx.desc,
success: function (res) {
//alert('已分享');
},
fail: function (res) {
//'分享失败!'
}
};
wx.onMenuShareAppMessage(shareData);
wx.onMenuShareTimeline(shareData);
wx.onMenuShareQQ(shareData);
wx.onMenuShareWeibo(shareData);
wx.onMenuShareQZone(shareData);
});
}