微信JSSDK

html屏蔽分享按鈕

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>test</title>
        <script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
        <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
        <script>
        var link = location.href;
        $(function() {
            wx.config({
                    debug: false, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來
                    appId: 'wx6fede0c9989aa98c', // 必填,公衆號的唯一標識
                    timestamp: "1513666450", // 必填,生成簽名的時間戳
                    nonceStr: "b5f88ccf-227a-41c9-9db3-d585ef6a933d", // 必填,生成簽名的隨機串
                    signature: "843f834527fc605de31303af5a5bfba97f406e1e",// 必填,簽名,見附錄1
                    jsApiList: [
                        "hideOptionMenu"
                    ] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2"closeWindow","hideOptionMenu","hideMenuItems","hideAllNonBaseMenuItem"
                });
                wx.ready(function () {
                    //wx.closeWindow({success:function(){alert("success")}});
                    /*wx.hideMenuItems({

                        menuList: ["menuItem:share:appMessage","menuItem:share:qq","/menuItem:share:QZone","menuItem:share:timeline"] // 要隱藏的菜單項,只能隱藏“傳播類”和“保護類”按鈕,所有menu項見附錄3

                    });*/
                    //wx.hideAllNonBaseMenuItem();
                    wx.hideOptionMenu();


                    /*wx.hideMenuItems({
                        menuList: ['menuItem:share:qq',
                                   'menuItem:share:weiboApp',
                                   'menuItem:favorite',
                                   'menuItem:share:facebook',
                                   '/menuItem:share:QZone']// 要隱藏的菜單項,只能隱藏“傳播類”和“保護類”按鈕,所有menu項見附錄3

                    });*/
                });
        });

    </script>
    </head>
    <body>
        <h1>jssdk屏蔽右上角分享按鈕。。</h1>
    </body>

</html>

springmvc控制器獲取簽名信息

/**
 *獲取簽名(簽名、隨機字符串、時間戳)
 */
@Controller
public class Sign {

    private static final String APPID = "wx6fede0c9989aa98c";//唯一標識
    private static final String APPSECRET = "b38cbaf67f9ee83e6441cde16a9bd32b";//密鑰
    @ResponseBody
    @RequestMapping(value="/sign",produces={"application/json;charset=UTF-8"})
    public String sign(HttpServletRequest request) throws ClientProtocolException, IOException {
        Map<String, String> ret = new HashMap<String, String>();
        String noncestr = UUID.randomUUID().toString();//生成簽名的隨機串
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);//時間戳
        String jsapi_ticket = WeiXinUtil.getJsAPI_ticket(APPID, APPSECRET);//需要動態生成,根據access_token發送https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=abc&type=jsapi
        String url = "http://127.0.0.1:8020/jssdk/index.html";//request.getParameter("url");//"http://bzzx.whonemap.cn:8799/WXYZT/index.jsp";//當前網頁的URL
        String string1;
        String signature = "";//簽名

        //注意這裏參數名必須全部小寫,且必須有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + noncestr +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");//提供SHA-1 or SHA-256算法
            crypt.reset();//重設
            crypt.update(string1.getBytes("UTF-8"));//對參數進行sha-1加密,使用指定的字節數組更新摘要
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", noncestr);
        ret.put("timestamp", timestamp);
        ret.put("url", url);
        ret.put("signature", signature);
        String signStr = JSONUtils.toJSONString(ret);
        return signStr;
    }

    //字節數組轉十六進制字符串
    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;
    }


}

獲取api_ticket

api_ticket 是用於調用微信卡券JS API的臨時票據,有效期爲7200 秒,通過access_token 來獲取。

/**
 * 獲取access_token和jsapi_ticket
 */
public class WeiXinUtil {
    //從微信後臺拿到APPID和APPSECRET 並封裝爲常量
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private static final String JSAPI_TICKET_UTL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
    /**
     * 編寫Get請求的方法。但沒有參數傳遞的時候,可以使用Get請求
     * 
     * @param url 需要請求的URL
     * @return 將請求URL後返回的數據,轉爲JSON格式,並return
     */
    public static JSONObject doGetStr(String url) throws ClientProtocolException, IOException {
        @SuppressWarnings({ "deprecation", "resource" })
        DefaultHttpClient client = new DefaultHttpClient();//獲取DefaultHttpClient請求
        HttpGet httpGet = new HttpGet(url);//HttpGet將使用Get方式發送請求URL
        JSONObject jsonObject = null;
        HttpResponse response = client.execute(httpGet);//使用HttpResponse接收client執行httpGet的結果
        HttpEntity entity = response.getEntity();//從response中獲取結果,類型爲HttpEntity
        if(entity != null){
            String result = EntityUtils.toString(entity,"UTF-8");//HttpEntity轉爲字符串類型
            jsonObject = JSONObject.fromObject(result);//字符串類型轉爲JSON類型
        }
        return jsonObject;
    }

    /**
     * 編寫Post請求的方法。當我們需要參數傳遞的時候,可以使用Post請求
     * 
     * @param url 需要請求的URL
     * @param outStr  需要傳遞的參數
     * @return 將請求URL後返回的數據,轉爲JSON格式,並return
     */
    public static JSONObject doPostStr(String url,String outStr) throws ClientProtocolException, IOException {
        DefaultHttpClient client = new DefaultHttpClient();//獲取DefaultHttpClient請求
        HttpPost httpost = new HttpPost(url);//HttpPost將使用Get方式發送請求URL
        JSONObject jsonObject = null;
        httpost.setEntity(new StringEntity(outStr,"UTF-8"));//使用setEntity方法,將我們傳進來的參數放入請求中
        HttpResponse response = client.execute(httpost);//使用HttpResponse接收client執行httpost的結果
        String result = EntityUtils.toString(response.getEntity(),"UTF-8");//HttpEntity轉爲字符串類型
        jsonObject = JSONObject.fromObject(result);//字符串類型轉爲JSON類型
        return jsonObject;
    }

    /**
     * 獲取AccessToken
     * @return 返回拿到的access_token及有效期
     */
    public static AccessToken getAccessToken(String APPID,String APPSECRET) throws ClientProtocolException, IOException{
        AccessToken token = new AccessToken();
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);//將URL中的兩個參數替換掉
        JSONObject jsonObject = doGetStr(url);//使用剛剛寫的doGet方法接收結果
        if(jsonObject!=null){ //如果返回不爲空,將返回結果封裝進AccessToken實體類
            token.setToken(jsonObject.getString("access_token"));//取出access_token
            int expires_in = jsonObject.getInt("expires_in");
            int currentTime = currentTime();
            int expires_out = expires_in + currentTime;
            token.setExpiresIn(expires_out);//取出access_token的有效期
        }
        return token;
    }

    /**
     * 獲取jsapi_ticket
     * @return 
     */
    public static String getJsAPI_ticket(String APPID,String APPSECRET) throws ClientProtocolException, IOException{
        String access_token = "";
        String jsapi_ticket = "";
        AccessToken config = readXml();
        if(currentTime()>=config.getExpiresIn()) {//如果token過期
            AccessToken token = getAccessToken(APPID, APPSECRET);
            access_token = token.getToken();
            String url = JSAPI_TICKET_UTL.replace("ACCESS_TOKEN", access_token);
            JSONObject jsonObject = doGetStr(url);//從微信獲取ticket
            if(jsonObject!=null) {
                jsapi_ticket = jsonObject.getString("ticket");
                token.setJsApiTicket(jsapi_ticket);
                writeXml(token);
            }
        }else {
            jsapi_ticket = config.getJsApiTicket();//如果token沒有過期,從配置文件獲取
        }
        return jsapi_ticket;
    }
    //獲取當前時間
    public static int currentTime() {
        return (int) (System.currentTimeMillis()/1000);
    }
    //讀配置文件
    public static AccessToken readXml() {
        AccessToken config = null;  
        InputStream is = WeiXinUtil.class.getResourceAsStream("/token.xml");
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(AccessToken.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();     // 從指定的文件解組 XML 數據並返回得到的內容樹。    
            config = (AccessToken) jaxbUnmarshaller.unmarshal(is);
            System.out.println(config);    
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }    // 創建一個可以用來將 XML 數據轉換爲 java 內容樹的 Unmarshaller 對象。    
        finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return config;
    }
    //寫配置文件,token重新獲取時
    public static void writeXml(AccessToken config) throws FileNotFoundException {
        URL url = WeiXinUtil.class.getResource("/token.xml");
        File file = new File(url.getFile()); 
        OutputStream os = new FileOutputStream(file); 
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(AccessToken.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();    // 從指定的文件解組 XML 數據並返回得到的內容樹。    
            jaxbMarshaller.marshal(config, os);
            System.out.println(config);    
        } catch (JAXBException e) {
            e.printStackTrace();
        }    // 創建一個可以用來將 XML 數據轉換爲 java 內容樹的 Unmarshaller 對象。    
        finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

JSSDK使用步驟

步驟一:綁定域名 先登錄微信公衆平臺進入“公衆號設置”的“功能設置”裏填寫“JS接口安全域名”。

步驟二:引入JS文件 在需要調用JS接口的頁面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.2.0.js

步驟三:通過config接口注入權限驗證配置 所有需要使用JS-SDK的頁面必須先注入配置信息,否則將無法調用(同一個url僅需調用一次,對於變化url的SPA的web

app可在每次url變化時進行調用,目前Android微信客戶端不支持pushState的H5新特性,所以使用pushState來實現web
app的頁面會導致簽名失敗,此問題會在Android6.2中修復)。 wx.config({
debug: true, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時纔會打印。
appId: ”, // 必填,公衆號的唯一標識
timestamp: , // 必填,生成簽名的時間戳
nonceStr: ”, // 必填,生成簽名的隨機串
signature: ”,// 必填,簽名,見附錄1
jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2 });

步驟四:通過ready接口處理成功驗證 wx.ready(function(){

// config信息驗證後會執行ready方法,所有接口調用都必須在config接口獲得結果之後,config是一個客戶端的異步操作,所以如果需要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則可以直接調用,不需要放在ready函數中。

});

步驟五:通過error接口處理失敗驗證 wx.error(function(res){

// config信息驗證失敗會執行error函數,如簽名過期導致驗證失敗,具體錯誤信息可以打開config的debug模式查看,也可以在返回的res參數中查看,對於SPA可以在這裏更新簽名。

});

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