美文网首页
web调用微信jssdk实现扫一扫

web调用微信jssdk实现扫一扫

作者: 聆听璇律 | 来源:发表于2019-01-04 16:35 被阅读29次

    一.微信公众号配置

    1.JS接口安全域名设置


    js安全域名.png

    2.IP白名单设置


    IP白名单.png

    二.JS文件的引入

    引入js文件,用来调用wx的接口

    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.0.js"></script>
    

    三.网页daunt调用jssdk的扫一扫

    (ps:config配置里面的参数通过后台签名后获取,网页端请求后台接口,获得config里面需要的参数)

    //wx.config验证权限配置
    wx.config({
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId: '', // 必填,公众号的唯一标识
        timestamp: , // 必填,生成签名的时间戳
        nonceStr: '', // 必填,生成签名的随机串
        signature: '',// 必填,签名,见附录1
        jsApiList: ['scanQRCode'] // 必填,需要使用的JS接口列表,这里只说扫描,例如分享等都可以,只要写在数组里面就可以调用
    });
    
    //权限验证出错
    wx.error(function(res) {
            alert("出错了:" + res.errMsg);
        });
     
    //授权通过
    wx.ready(function() {
        wx.checkJsApi({
            jsApiList : ['scanQRCode'],
            success : function(res) {
    wx.scanQRCode({
                    needResult: 1,
                    desc: 'scanQRCode desc',
                    success: function(res) {
                    var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果                    
            }
        });
    });
    

    四.后台签名

    微信开发原文档
    签名之前我们得要准备微信公众号的appId和appSecret,通过他们获取token

     public static String getToken(String appid, String appSecret) throws ClientProtocolException, IOException {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            // 创建参数队列
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("grant_type", "access_token"));
            params.add(new BasicNameValuePair("appid", appid));
            /* secret */
            params.add(new BasicNameValuePair("appid", appSecret));
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret="
                    + appSecret;
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 发送请求
            CloseableHttpResponse response = httpclient.execute(httpget);
            // 得到响应提
            HttpEntity entity = response.getEntity();
    
            String param = EntityUtils.toString(entity);
            System.out.println(param);
            // 将JSON转换为Map
            Map parseParam = (Map) JSON.parse(param);
            Object object = parseParam.get("access_token");
            return object.toString();
        }
    

    然后通过token获取jsapi_ticket

    public static String getJsapi_ticket(String access_token) {
            String ticket = "";
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token
                    + "&type=jsapi";
            CloseableHttpClient httpclient = HttpClients.createDefault();
            // 先从线程中取值,如果取不到,说明没有使用线程,再利用这个方法获取
            // 因为发送信息等操作,都是调用的这个方法,所以在这里进行处理一下吧
            HttpGet httpget = new HttpGet(requestUrl);
            // 发送请求
            CloseableHttpResponse response = null;
            try {
                response = httpclient.execute(httpget);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // 得到响应提
            HttpEntity entity = response.getEntity();
    
            String param = null;
            try {
                param = EntityUtils.toString(entity);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(param);
            // 将JSON转换为Map
            Map parseParam = (Map) JSON.parse(param);
            Object object = parseParam.get("ticket");
            return object.toString();
        }
    

    下面我们就正式签名了,签名的时候我们需要网页端给我们传过来页面的url(记住是完整url包括get后跟的参数(#不要))

    public class Sign {
        //网页端当前的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 +
                      "&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();
            }
    
            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);
        }
    }
    

    然后就可以在网页端调用扫一扫功能了

    相关文章

      网友评论

          本文标题:web调用微信jssdk实现扫一扫

          本文链接:https://www.haomeiwen.com/subject/qmshrqtx.html