您的位置:首页 > 移动开发 > 微信开发

微信JS-SDK自定义分享链接

2015-11-02 16:41 901 查看
微信自带的分享链接是不带参数的,开发过程如果要实现用户分享给予奖励等活动,需要自定义微信的分享链接,即调用微信js-sdk接口自定义分享链接。

调用微信官方提供的js接口,需要使用微信签名;

一:签名的获取流程

1.首先由微信appId与秘钥获取令牌(令牌是计算机安全中的一个概念,用于唯一区别一个用户)

备注:获取令牌后的有效时间是7200秒

[code]/**
*获取令牌access_token
*/
    private static String getAccess_token() {
        public  String APP_ID = "***********";//微信id
        public  String APP_SECRET="*********";//微信秘钥
        //微信令牌请求网址(由微信提供)
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
        String accessToken = null;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            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 = new JSONObject(message);
            accessToken = demoJson.getString("access_token");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }


2.利用令牌获取微信票据(票据时调用微信js接口的一个凭证)

备注:由于令牌有有效期限制,所以票据也是7200秒的有效期,而且微信js接口的调用每天有调用次数的限制, 因此用户获取票据后需要先存储起来(例如:放到一个静态map变量中(类似于全局变量)),每次需要票据时候先取本地的如果过期则需要重新生成一个新的票据。

[code]/**
*根据令牌获取调用微信的票据jsapi_ticket
*/  
    public static String getTicket(String access_token) {
        String ticket = null;
        //获取票据的网址(由微信提供)
        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();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            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 = new JSONObject(message);
            ticket = demoJson.getString("ticket");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ticket;
    }


3.获取微信签名

备注:调用后台sign方法,把一些参数信息放入到map中传到前台,用于调用微信的分享链接。

[code]/**
*根据票据调用微信官方接口,获取微信签名
* jsapi_ticket:票据
* url:网页地址()
*/  
    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);
    }


二:JSP页面调用微信JS接口生成自定义分享链接

[code]/**
* jsp页面上利用js调用微信官方接口,生成自定义带参数的分享链接。
*/  
    <script type="text/javascript">
$(function(){
    var currentUrl = location.href.split('#')[0];
    $.post("${path}/wx/account/get_weixin_data.html",{currentUrl:currentUrl},function(res){//post调用java后台,生成url
        var obj = JSON.parse(res);
        var title = "分享标题!";
        //分享url
        var sharedLink = location.host+"/wx/account/go/share.html?referrer=${wx_loginuser.uid}";
        //分享时候显示的图片
        var imgUrl = location.host+"/images/wx/ty.gif";
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: obj.appId, // 必填,公众号的唯一标识
            timestamp: obj.timestamp, // 必填,生成签名的时间戳
            nonceStr: obj.nonceStr, // 必填,生成签名的随机串
            signature: obj.signature,// 必填,签名,见附录1
            jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage'] // 必填,需要使用的JS接口列表,
        });
        wx.ready(function(){ //通过ready接口处理成功验证,需要把相关接口放在ready函数中调用来确保正确执行
        //实现JS分享功能
            wx.onMenuShareTimeline({//1.获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
                title: title, // 分享标题
                link: sharedLink, // 分享链接
                imgUrl: imgUrl, // 分享图标
                success: function () { 
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () { 
                    // 用户取消分享后执行的回调函数
                }
            });
            wx.onMenuShareAppMessage({//2.获取“分享给朋友”按钮点击状态及自定义分享内容接口
                title: title, // 分享标题
                desc: '', // 分享描述
                link: sharedLink, // 分享链接
                imgUrl: imgUrl, // 分享图标
                type: '', // 分享类型,music、video或link,不填默认为link
                dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
                success: function () { 
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () { 
                    // 用户取消分享后执行的回调函数
                }
            });
        });
    });
});
</script>


三:参考文件

1.方倍工作室—微信公众平台开发

http://www.cnblogs.com/txw1958/p/weixin-js-sharetimeline.html

2. 微信JS-SDK说明文档

http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: