React 框架下的 微信 JS-SDK 调用方法

项目使用React 开发 作为微信企业号应用 需要的功能为 获取地理位置信息

1.引入 JS文件

在public文件夹下的 Index.html 中引入 ,放在title标签下即可


 

2.设置 config

2.1 config 中需要配置四个参数

  1. appId:'wxxxxxxxxxx', // 必填,企业号的唯一标识,此处填写企业号corpid

  2. timestamp: timeStap, // 必填,生成签名的时间戳(10位)

  3. nonceStr: 'xxxx', // 必填,生成签名的随机串,注意大小写

  4. signature: result["signature"],// 必填,签名,见附录1(通过https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign 验证)

其中 比较重要的是 signature

signature 需要通过 后端接口 访问微信的 api 获取 access_token 后获取 jsapiTicket

拼接结束后 使用 SHA1算法加密后传回 即是可用的 signature

2.2 SHA1算法java 实现

 /**
     * SHA1签名算法
     * @param str
     * @return
     */
    public static String getSha1(String str) {

        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }

2.3 获取接口

后端获取 signature 接口

signature 拼接时候需严格按照 如下格式进行拼接

"jsapi_ticket=xxxxxx&noncestr=xxxx×tamp=xxxxx&url=http://xxxxxxxxx"

在IOS客户端 和 ANDROID中 url 参数略有不同

IOS客户端中 需要的是 页面的根路径

ANDROID客户单中需要的是当前页面的路径

注意: api 调用为单个应用每小时最多100次 实际测试可能小于100 接口就会无法相应 应当保存 jsapi_ticket避免频繁请求(本业务压力有限没有做处理)

java Spring-boot实现

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;


// 使用了 hutool 工具类下的一些http 访问 微信的api

/**
     * 获取定位信息所需的
     * @param timeStap
     * @return
     * @throws Exception
     */
    @CrossOrigin
    @RequestMapping(value = "/position", method = RequestMethod.GET)
    public JSONObject getUserIp(String timeStap) throws Exception {


        //获取accesstoken
        String accessTokenResult= HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=xxxxxxx&corpsecret=xxxxxxxxx");

        JSONObject accessTokenResultJson = JSONUtil.parseObj(accessTokenResult);


        //通过accesstoken获取jsapi_ticket
        String jsapiTicketResult = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token="+accessTokenResultJson.get("access_token"));

        JSONObject jsapiTicketResultJson = JSONUtil.parseObj(jsapiTicketResult);


        //拼接字符串
        String str = "jsapi_ticket="+jsapiTicketResultJson.get("ticket")+"&noncestr=const×tamp="+timeStap+"&url=http://htjoa.nrnet.cn/dc14/const/sign";

        //可以在微信企业号开发网页中验证  

        JSONObject jsonObject = JSONUtil.createObj();
        jsonObject.putOnce("code", "200");
        jsonObject.putOnce("msg", "成功");
        jsonObject.putOnce("jsapi_ticket",jsapiTicketResultJson.get("ticket"));
        jsonObject.putOnce("str",str);
        jsonObject.putOnce("signature",getSha1(str));  //调用上述的加密算法
        return jsonObject;
    }

3. 引入方式

使用函数式先注册config


export function jsSdkConfig() {
    //TODO 根据手机类型生成对应url

    //IOS 端需要从根url 中生成
    //ANDROID 需要从本路径下生成

    // let u = window.navigator.userAgent;
    // let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    // let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    // //安卓需要使用当前URL进行微信API注册(即当场调用location.href.split('#')[0])
    // //iOS需要使用进入页面的初始URL进行注册,(即在任何pushstate发生前,调用location.href.split('#')[0])
    // let url = '';
    // if (isiOS) {
    //     url = encodeURIComponent(`http://www.qq.com/home/index?op=${window.sessionStorage.getItem('option')}`);//获取初始化的url相关参数
    // } else {
    //     url = encodeURIComponent(window.location.href.split('#')[0]);
    // }

    const  timeStap = new Date().getTime().toString().substr(0,10);
    const  path = "http://xxxxxxxxxxx/xxxx/xxxxx/wechat/position?timeStap="+timeStap;

    fetch(path,{method:"GET"})
        .then(res=>res.json())
        .then(result=>{
            window.wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId:'wxxxxxxxxxxxxxx', // 必填,企业号的唯一标识,此处填写企业号corpid
                timestamp: timeStap, // 必填,生成签名的时间戳(10位)
                nonceStr: 'const', // 必填,生成签名的随机串,注意大小写
                signature: result["signature"],// 必填,签名,见附录1(通过https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign 验证)
                jsApiList: [
                    'getLocation',
                ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
            });
        });
}

调用地理位置信息
先引入config 注册函数 再使用window.wx.接口名称即可调用

        //直接调用函数注册 conifg
jsSdkConfig();

            //使用 window.wx.xxx调用对应的接口  可以将获取到的值存储 state  本项目使用的是class 故采用的 是setState方法
       window.wx.getLocation({
            type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
            success: function (res) {
                const latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
                const longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
                console.log(longitude,latitude)
                cookie.save("position",longitude+","+latitude);
                const speed = res.speed; // 速度,以米/每秒计
                const accuracy = res.accuracy; // 位置精度
            }
        });

你可能感兴趣的:(React 框架下的 微信 JS-SDK 调用方法)