微信自定義分享最新版

 java 代碼

private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',  
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

/**
     * 獲取簽名算法
     */
    public void jsapiTicket(){
        String url = getPara("url");
        Map<Object,Object> map = new HashMap<>();
        HttpServletRequest request = getRequest();
        Cookie[] cookies = request.getCookies();
        boolean flag = true;
        String access_token = "";
        //如果cookie 不等於空
        System.out.println("11111111111111111111111111111");
        if(null!=cookies){
            //先判斷cookie中的access_token 過期沒有
            for( int i=0; i<cookies.length; i++ ) {
                Cookie cookie = cookies[i];
                System.out.println( "Cookie name:"+cookie.getName() );
                System.out.println( "Cookie value:"+cookie.getValue() );
                System.out.println( "Max Age: "+cookie.getMaxAge()+"<br>" );
                if(cookie.getName().equals("access_token")) {
                    flag = false;
                    access_token = cookie.getValue();
                }
            }
        }
        System.out.println("33333333333333333333333333");
        String body = "";
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        System.out.println("4444444444444444444444444444");
        //如果過期了就重新獲取access_token
        if(flag){
            //獲取access_token
            body = HttpKit.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret);
            System.out.println(body);
            JSONObject jsonObject = JSONObject.fromObject(body);
            System.out.println(jsonObject.containsKey("access_token"));
            if(jsonObject.containsKey("access_token")){
                access_token = jsonObject.getString("access_token");
                System.out.println(access_token);
                Cookie cookie = new Cookie("access_token", access_token);
                cookie.setMaxAge(7200);
            }else{
                map.put("msg", "獲取失敗");
                map.put("code", 0);
                renderJson(map);
                return;
            }
        }
        //獲取到jsapi_ticket 並返回
        String doGet = HttpKit.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi");
        System.out.println(doGet);
        JSONObject jsonObject = JSONObject.fromObject(doGet);
        if(jsonObject.containsKey("ticket")){
            String jsapi_ticket = jsonObject.getString("ticket");
            Record record = new Record();
            //jsapi_ticket
            record.set("jsapi_ticket", jsapi_ticket);
            //appId
            record.set("appId", appId);
            //時間戳
            long timestamp = System.currentTimeMillis() / 1000;
            record.set("timestamp", timestamp);
            //隨機字符串
            String nonceStr = UUID.randomUUID().toString();
            record.set("nonceStr", nonceStr);
            String signature = "jsapi_ticket="+jsapi_ticket+"&noncestr="+nonceStr+"&timestamp="+timestamp+"&url="+url;
            System.out.println("22222222222222222222222222222222");
            signature = encode(signature);
            //簽名
            record.set("signature", signature);
            record.set("url", url);
            map.put("msg", "獲取成功");
            map.put("code", 1);
            map.put("data", record);
        }else{
            map.put("msg", "獲取失敗");
            map.put("code", 0);
        }
        renderJson(map);
    }
    
    /**
     * 首字母排序
     */
    public static void sortStringArray() {
        String[] arrayToSort = new String[] { "jsapi_ticket", "appId", "timestamp",
        "nonceStr", "url"};
        System.out.println();
        System.out.println("字符型數組排序,排序前:");
        for (int i = 0; i < arrayToSort.length; i++){
        System.out.print(arrayToSort[i]+",");
        }
        System.out.println();
        System.out.println("排序後:");
        // 調用數組的靜態排序方法sort,且不區分大小寫
        Arrays.sort(arrayToSort,String.CASE_INSENSITIVE_ORDER);
        for (int i = 0; i < arrayToSort.length; i++){
        System.out.print(arrayToSort[i]+"=&");
        }
    }
    
    public static String encode(String string1) {
        String signature = "";

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

js 代碼

var imgUrl = 'http://xxx';  // 分享後展示的一張圖片
var lineLink = 'http://xxx'; // 點擊分享後跳轉的頁面地址
var descContent = "描述信息描述信息描述信息描述信息描述信息描述信息";  // 分享後的描述信息
var shareTitle = '標題標題標題標題';  // 分享後的標題
var appid = '';  // 應用id,如果有可以填,沒有就留空
	$(function(){
		$.ajax({
			type:"POST",
			dataType:"json",
			data:{"url":window.location.href},
			url:"${base}/jsapiTicket",
			success:function(res){
				//通過config接口注入權限驗證配置
				var data = res.data;
				console.log(res);
				if(res.code==1){
					wx.config({
					    debug: false,// 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。移動端會通過彈窗來提示相關信息。如果分享信息配置不正確的話,可以開了看對應報錯信息
					    appId: data.appId,
					    timestamp: data.timestamp,
					    nonceStr: data.nonceStr,
					    signature: data.signature,
					    jsApiList: [//需要使用的JS接口列表,分享默認這幾個,如果有其他的功能比如圖片上傳之類的,需要添加對應api進來
					        'updateAppMessageShareData',//
					        'updateTimelineShareData',
					        'checkJsApi'
					    ]
					});
					wx.checkJsApi({
					    jsApiList: ['updateAppMessageShareData','updateAppMessageShareData'], // 需要檢測的JS接口列表,所有JS接口列表見附錄2,
					    success: function(res) {
					    	console.log(res);
					    }
					});
					wx.ready(function () {
						wx.updateAppMessageShareData({ 
					        title: shareTitle, // 分享標題
					        desc: descContent, // 分享描述
					        link: lineLink, // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公衆號JS安全域名一致
					        imgUrl: imgUrl, // 分享圖標
					        success: function () {
					          // 設置成功
					        }
					    })
						wx.updateTimelineShareData({ 
					        title: shareTitle, // 分享標題
					        link: lineLink, // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公衆號JS安全域名一致
					        imgUrl: imgUrl, // 分享圖標
					        success: function () {
					          // 設置成功
					        }
					    })
				    });
					wx.error(function(res) {
						// config信息驗證失敗會執行error函數,如簽名過期導致驗證失敗,具體錯誤信息可以打開config的debug模式查看,也可以在返回的res參數中查看,對於SPA可以在這裏更新簽名。
						alert('error');
					});
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
			     console.log(XMLHttpRequest.status);
			     console.log(XMLHttpRequest.readyState);
			        console.log(textStatus);
			  }
		});
	});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章