在微信里进行网页开发的主要目的是能使用微信的jssdk,从而可以操作手机上的硬件设备。实际操作步骤如下:
准备工作:
1,微信公众号进行微信认证
2,服务器,添加上合法域名,并且对外端口一定要80(微信也省的去再认证)。
一.首先进行js认证:域名/工程名或者域名/工程/路径。如:JS接口安全域名 :weixin.huatugz.com/Its-weixin-appraise 并将MP_verify_MLRjtGQmYHiUnsI7.txt放在工程目录Its-weixin-appraise下面。
二.引入微信JS文件,jweixin-1.2.0.js,在使用的网页内引用即可。
三.进行第四步之前,先要运行第三部,获取到调用微信JS接口的临时票据jsapi_ticket。启动工程时运行一次,之后每隔7200秒运行一次,并保存公共变量jsapi_ticket。获取的逻辑可参考微信JS-SDK附录1
public class WeiXinConfigLister extends HttpServlet{
private static final long serialVersionUID = 275178889L;
public void init(ServletConfig config) throws ServletException {
String url="https://api.weixin.qq.com/cgi-bin/token";
String param="grant_type=client_credential&appid=wxe91ea5de6c7dc2a9&secret=dc9f3a332b761e4fefb7935f26dd32a1";
String ret = HttpRequest.sendGet(url, param);
JSONObject aray= JSONObject.fromObject(ret);
GlobalVariant.access_token = aray.getString("access_token");
String urlcgi="https://api.weixin.qq.com/cgi-bin/ticket/getticket";
String paramcgi="access_token="+GlobalVariant.access_token+"&type=jsapi";
String retcgi = HttpRequest.sendGet(urlcgi, paramcgi);
JSONObject araycgi= JSONObject.fromObject(retcgi);
GlobalVariant.ticket = araycgi.getString("ticket");
}
}
四.配置config接口注入权限验证(每次进入页面都需要验证这个页面需要用到的权限)。因此配置ajax,每次进入网页运行一次。
$.ajax({
url : "weixinconfig.html",
type : 'post',
dataType : 'json',
data : {
'url' : location.href.split('#')[0]
},
success : function(data) {
wx.config({
debug : false,
appId : data.appId,
timestamp : data.timestamp,
nonceStr : data.nonceStr,
signature : data.signature,
jsApiList : [ 'onMenuShareTimeline','chooseImage','onMenuShareAppMessage' ]
});
}
});
ajax url : "weixinconfig.html",进入的后台程序,返回数据如下:(本数据处理逻辑微信文档写的很清楚,可深入查看)
public class SetConfigServiceImpl implements SetConfigService{
@Override
public JSONObject getConfigData(HttpServletRequest request,
HttpServletResponse response,String url) throws SQLException {
// TODO Auto-generated method stub//系统生成uuid
String nonceStr=CreateNonceStr();//系统生成时间
String timestamp=CreateTimesTamp();//微信生成的ticket,7200秒更新一次。由另一个接口处理,这里只需要调用更新后的公共变量即可。
String ticket=GlobalVariant.ticket;
String signature = "";
String ticstring = "jsapi_ticket=" + ticket +
"&noncestr=" + nonceStr +
"×tamp=" + timestamp +
"&url=" + url;
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(ticstring.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
JSONObject retjson= new JSONObject();
retjson.put("appId", GlobalVariant.appId);
retjson.put("timestamp", timestamp);
retjson.put("nonceStr", nonceStr);
retjson.put("signature", signature);
return retjson;
}
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
private static String CreateTimesTamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
private static String CreateNonceStr() {
return UUID.randomUUID().toString();
}
@Override
public void getData(HttpServletRequest request,
HttpServletResponse response) throws SQLException {
// TODO Auto-generated method stub
}
}
前四步的配置对网页开发已经够了,可进行微信网页开发。
五.(启用并设置服务器配置后,用户发给公众号的消息以及开发者需要的事件推送,将被微信转发到该URL中)在微信管理界面出,开发-->基本配置,配置接入服务器。需要自己服务器上建立相应的验证接口。
public class UilVerify extends HttpServlet{
private static final long serialVersionUID = 12586876L;
private static final String tokens = "huatugzverify";
public UilVerify(){
super();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
String signature = req.getParameter("signature");
String timestamp = req.getParameter("timestamp");
String nonce = req.getParameter("nonce");
String echostr = req.getParameter("echostr");
PrintWriter out = resp.getWriter();
if (isWeixin(signature, timestamp, nonce)) {
out.print(echostr); // 校验通过,原样返回echostr参数内容
}
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
protected static boolean isWeixin(String signature,String timestamp,String nonce){
String[] arr = new String[] { tokens, timestamp, nonce };
// 排序
Arrays.sort(arr);
// 生成字符串
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
// sha1加密
String temp = getSHA1String(content.toString());
return temp.equals(signature); // 与微信传递过来的签名进行比较
}
private static String getSHA1String(String data){
return DigestUtils.sha1Hex(data); // 使用commons codec生成sha1字符串
}
}