JAVA H5微信分享
一、前台代码:
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <script type="text/javascript"> $(function(){ var str = $(window).height(); $('#btn').css("margin-top",str*0.58); $('#Layer1').css("margin-top",str*0.06); }) wx.config({ // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: '${map.appId}', // 必填,公众号的唯一标识 timestamp: '${map.timestamp}', // 必填,生成签名的时间戳 nonceStr: '${map.nonceStr}', // 必填,生成签名的随机串 signature: '${map.signature}',// 必填,签名,见附录1 jsApiList: [ 'onMenuShareAppMessage' ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); wx.ready(function(){ var sdata = { title: '下载xxapp', desc: '移动xxAPP上线拉快来下载呀!!', link: 'http://www.xx.com/operation/mybusi/barcode', imgUrl: 'http://www.xx.com/images/h5/microcode/60.png', success: function () { // alert('用户确认分享后执行的回调函数'); }, cancel: function () { // alert('用户取消分享后执行的回调函数'); } }; // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。 wx.onMenuShareAppMessage(sdata); }); </script>
二、java后台代码:
package com.unionpay.acp.sdk; import java.util.UUID; import java.util.Map; import java.util.HashMap; import java.util.Formatter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.io.UnsupportedEncodingException; import net.sf.json.JSONObject; import com.xx.common.config.Global; import com.unionpay.acp.sdk.HttpClient; /** * 微信分享签名 * */ public class Sign { public static void main(String[] args) { // String jsapi_ticket = "kgt8ON7yVITDhtdwci0qecRXz9HyXuyXgIslzmd3ri0s5EnLrVZZfrPJotRfKWQ-TTuQ2ZMAK86GUlWF1PHhcg"; }; public static Map<String, String> getResult(){ // String jsapi_ticket = getTicket(); // 注意 URL 一定要动态获取,不能 hardcode String url = "http://www.xx.com/operation/mybusi/barcode"; // String url = Global.getConfig("wx.shareUrl"); Map<String, String> ret = sign(getTicket(), url); ret.put("appId", getAppId()); return ret; } private static String getAppId(){ return Global.getConfig("wx.appid"); } private static String getToken(){ String accessToken = ""; String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+getAppId()+"&secret="+Global.getConfig("wx.secret"); HttpClient hc = new HttpClient(url, 30000, 30000); try { int status = hc.sendGet("utf-8"); if (200 == status) { String resultString = hc.getResult(); if (null != resultString && !"".equals(resultString)) { JSONObject json = JSONObject.fromObject(resultString); if (null==json.get("errcode")){ accessToken = json.get("access_token").toString(); } else { System.out.println(resultString); } } }else{ System.out.println("返回http状态码["+status+"],请检查请求报文或者请求地址是否正确"); } } catch (Exception e) { e.printStackTrace(); } return accessToken; } private static String getTicket(){ String ticket = ""; String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+getToken()+"&type=jsapi"; HttpClient hc = new HttpClient(url, 30000, 30000); try { int status = hc.sendGet("utf-8"); if (200 == status) { String resultString = hc.getResult(); if (null != resultString && !"".equals(resultString)) { JSONObject json = JSONObject.fromObject(resultString); if ("0".equals(json.getString("errcode"))){ ticket = json.getString("ticket"); } else { System.out.println(resultString); } } }else{ System.out.println("返回http状态码["+status+"],请检查请求报文或者请求地址是否正确"); } } catch (Exception e) { e.printStackTrace(); } return ticket; } public static Map<String, String> sign(String jsapi_ticket, String url) { Map<String, String> ret = new HashMap<String, String>(); String nonce_str = create_nonce_str(); String timestamp = create_timestamp(); 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 (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; } 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 create_nonce_str() { return UUID.randomUUID().toString(); } private static String create_timestamp() { return Long.toString(System.currentTimeMillis() / 1000); } }