微信分享

WEB前端 waitig 454℃ 百度已收录 0评论

scrm/agentactivities.jsp

<div class="tcamera"  onclick="pop_mask(this)"><a href="#">分享与代理</a></div>
var timestamp = "<%= request.getSession().getAttribute("timestamp")%>";
    var nonceStr = "<%= request.getSession().getAttribute("nonceStr")%>";
    var signature = "<%= request.getSession().getAttribute("signature")%>";
    var agid = "<%= request.getSession().getAttribute("opid")%>";
    var aid = null;
    var uid = ${addUser.id};
    var appid = "${appid}";
    $(function() {
        //微信分享开始
        getWXParams();
        WXConfig();

        wx.error(function (res) {
            // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
            //alert("errormsg="+ JSON.stringify(res));
        });
    })
//微信分享结束

//获取WXParmas
    function getWXParams(){
        var url=location.href;
//         url = encodeURIComponent(url);
        $.ajax({
            type: 'GET',
            url: '../activity/getWXUploadParams',
            async:false,
            data:{"url":location.href.split('#')[0]},
            dataType: 'json',
            success: function(data){
                console.log(data);
                timestamp = data.rows[0];
                nonceStr = data.rows[1];
                signature = data.rows[2];

            },
            error:function(){
            }
        });

    }

    function WXConfig(){
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: appid, // 必填,公众号的唯一标识
            timestamp: timestamp, // 必填,生成签名的时间戳
            nonceStr: nonceStr, // 必填,生成签名的随机串
            signature: signature,// 必填,签名,见附录1
            jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
        });
    }
/* 分享 */
    function pop_mask(val){
        var id = $($(val).parent().siblings()[1]).text();
        aid = id;
        $("#tmask").css("display","block");
        $("#pro_mask_fen").css("display","block");
        wx.ready(function () {
            wx.checkJsApi({
                jsApiList: [
                    'getNetworkType',
                    'previewImage'
                ],
                success: function (res) {
//                  alert("checkJsApi==" + JSON.stringify(res));
                }
            });
            //分享到朋友圈
            wx.onMenuShareTimeline({
                title: 'IT新人来报名', // 分享标题
                link: 'http://test4.easyinlab.org/scrm/user/share?agid=' + agid+'&aid='+aid, // 分享链接
                imgUrl: 'http://oz1h9kuzx.bkt.clouddn.com/095d251681b9428bacc2fe2f2d10c81d_1510117452668.jpg', // 分享图标
                success: function () {
                    alert("分享到朋友圈成功");
                    pop_maskclose();
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });

            // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
            //分享给朋友
            wx.onMenuShareAppMessage({
                title: 'IT新人来报名', // 分享标题
                desc: 'IT新人来报名', // 分享描述
                link: 'http://test4.easyinlab.org/scrm/user/share?agid=' + agid+'&aid='+aid, //分享的链接
                imgUrl: 'http://oz1h9kuzx.bkt.clouddn.com/095d251681b9428bacc2fe2f2d10c81d_1510117452668.jpg', // 分享图标
                type: 'link', // 分享类型,music、video或link,不填默认为link
                //dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                    alert("分享到好友成功");
                    pop_maskclose();
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
        });
    }

controller中 :

/**
     *
     * @Title: getWXUploadParms
     * @Description: (获取微信上传接口参数:acess_token,jsapi_ticket,signature)
     * @return String
     * @return
     * @author  Yi.Qiao
     * @date 2017年10月30日 下午3:53:45
     */
    @ResponseBody
    @RequestMapping(value="/getWXUploadParams",produces ="application/json;charset=utf-8")
    public String getWXUploadParams(HttpServletRequest request, HttpSession session,String url){
        session = request.getSession();
        String nonceStr = WXUtil.create_nonce_str();
        String timestamp = WXUtil.create_timestamp();
        String acess_token = WXUtil.getAccessToken();
        String jsapi_ticket = WXUtil.getJSApiTicket(acess_token);

        String signature = WXUtil.getSignature(jsapi_ticket,nonceStr,timestamp,url);
//      String signature = "220a241a342d8a637507a79bf5dcf6aabafa9663";
        session.setAttribute("nonceStr", nonceStr);
        session.setAttribute("timestamp", timestamp);
        session.setAttribute("signature", signature);
        System.out.print("jsapi_ticket**************************:"+jsapi_ticket);
        System.out.print("nonceStr**************************:"+nonceStr);
        System.out.print("timestamp**************************:"+timestamp);
        System.out.print("signature**************************:"+signature);
        System.out.print("url**************************:"+url);
        session.setMaxInactiveInterval(7200);//设置过期时间为30分钟/7200秒
        List<String> listStr =  new ArrayList<String>();
        listStr.add(timestamp);
        listStr.add(nonceStr);
        listStr.add(signature);
        System.out.println("------------------------------------------------------------------------------");
        System.out.println(session.getAttribute("signature"));
        System.out.println("------------------------------------------------------------------------------");
        if (nonceStr!=null&&timestamp!=null&&signature!=null) {
            return JSONUtil.toResultJSON(listStr);
        }
        return "400";
    }

WXUtil :

package org.easyinlab.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;

public class WXUtil {
     public static String sendGet(String url, String charset, int timeout)
     {
       String result = "";
       try
       {
         URL u = new URL(url);
         try
         {
           URLConnection conn = u.openConnection();
           conn.connect();
           conn.setConnectTimeout(timeout);
           BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
           String line="";
           while ((line = in.readLine()) != null)
           {

             result = result + line;
           }
           in.close();
         } catch (IOException e) {
           return result;
         }
       }
       catch (MalformedURLException e)
       {
         return result;
       }

       return result;
     }


     /***
      * 获取acess_token 
      * 来源www.vxzsk.com
      * @return
      */
     public static String getAccessToken(){
            String appid=ParameterUtil.APPID;//应用ID
            String appSecret=ParameterUtil.APPSECRET;//(应用密钥)
            String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appSecret+"";
            String backData=WXUtil.sendGet(url, "utf-8", 10000);

            String accessToken  =  (String) JSONObject.parseObject(backData).get("access_token");
            return  accessToken ;
     }
    //获取code
    public  String getCode(){
//        String appid=ParameterUtil.APPID;//应用ID
//        String appSecret=ParameterUtil.APPSECRET;//(应用密钥)
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize?"
                + "appid=wx6d6fb2eddd9345a7"
                + "&redirect_uri=http%3a%2f%2ftest4.easyinlab.org%2fscrm%2fuser%2flogin"
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=easyinlab#wechat_redirect";
        String backData=WXUtil.sendGet(url, "utf-8", 10000);
        System.out.println("code+++++++"+backData);
//        String code  =  (String) JSONObject.parseObject(backData).get("code");
        return  backData ;
    }

    //删除菜单
    public static String deleteView(String accessToken){
        String url ="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", accessToken);
        String backData=WXUtil.sendGet(url, "utf-8", 10000);
        System.out.println("delete:"+backData);
//        String code  =  (String) JSONObject.parseObject(backData).get("code");
        return  backData ;
    }

     public static String getJSApiTicket(String acess_token){ 
         //获取token
//         String acess_token= WXUtil.getAccessToken();
         String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+acess_token+"&type=jsapi";  
         String backData=WXUtil.sendGet(urlStr, "utf-8", 10000);  
         String ticket = (String) JSONObject.parseObject(backData).get("ticket");  
         return ticket;  
     }  
     //获取signature
     public static String getSignature(String jsapi_ticket,String nonce_str,String timestamp, String url) {
         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();
         }

         return signature;
     }

     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;
     }

     public static String create_nonce_str() {
         return UUID.randomUUID().toString();
     }

     public static String create_timestamp() {
         return Long.toString(System.currentTimeMillis() / 1000);
     }
}

本文由【waitig】发表在等英博客
本文固定链接:微信分享
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)