微信公众号JSSDK分享


后台获取wx.config签名验证数据

@RequestMapping(value = "pay_wx_config", method = RequestMethod.POST)
@ResponseBody
public SimpleResult pay_wx_config() {
    SimpleResult result = new SimpleResult();

    //java 获取请求 URL
    String current_url = config.getHost();
    current_url += this.getRequest().getRequestURI();     // 工程名
    if (this.getRequest().getQueryString() != null) //判断请求参数是否为空
    {
        current_url += "?" + this.getRequest().getQueryString();
    }   // 参数
    try {
        ParameterMap pm = this.getParameterMap();
        if(StringUtils.isNotBlank(pm.getString("current_url"))){
            current_url = pm.getString("current_url");
        }
        System.out.println("----" + current_url);
        String url = "";
        String resultstr = "";
        JSONObject object = null;
        Map<String, String> params = new HashMap<String, String>();
        params.put("1", "1");
        MyPayConfig myconfig = new MyPayConfig(config);
        WXPay wxpay = new WXPay(myconfig);
        String token = WechatAppAccessToken.getAppAccessToken();
        String ticket = WechatAppAccessToken.getJsapiTicket(token);
        String timestamp = WxSign.create_timestamp();
        //todo sha1 之后的签名
        Map signMap = WxSign.sign(ticket, current_url);
        signMap.put("appId", config.getAppId());
        System.out.println(JSONUtil.toJson(signMap));
        result.setData(signMap);
        result.setResult(HttpStatus.OK.getStatusCode());
        result.setMessage("获取WxConfig成功");

    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        result.setResult(HttpStatus.BAD_REQUEST.getStatusCode());
        result.setMessage("获取WxConfig失败");
        result.setErrorMsg(e.getMessage());
    }
    return result;
}



前台JSdemo

$.ajax({
    url: 'pay_wx_config',
    data: {current_url:window.location.href},
    type: "POST",
    dataType: "json",
    async: false,
    success: function (res) {
        if(res!=null && res.result==200){
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: res.data.appId, // 必填,公众号的唯一标识
                timestamp: res.data.timestamp, // 必填,生成签名的时间戳
                nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
                signature: res.data.signature,// 必填,签名
                jsApiList: ['chooseWXPay', 'onMenuShareTimeline', 'hideOptionMenu', 'onMenuShareAppMessage'] // 必填,需要使用的JS接口列表
            });

            wx.ready(function() {
                wx.onMenuShareTimeline({
                    title: '小菜,厨房里的健康菜', // 分享标题
                    link: LINK_URL+'/app_index?locationFlag=1&pid='+getCookie('APP_USER_ID'), // 分享链接
                    imgUrl: 'https://baonuotest.oss-cn-beijing.aliyuncs.com/bainuo/e8590187-75b0-4115-aaad-2155bb20be08.jpg', // 分享图标
                    success: function () {
                        // 用户确认分享后执行的回调函数
                        // alert("分享成功");
                    },
                    cancel: function () {
                        // 用户取消分享后执行的回调函数
                        // alert("取消分享");
                    }
                });

                wx.onMenuShareAppMessage({
                    title: '小菜,厨房里的健康菜', // 分享标题
                    desc: '首单立减20元!天天低价享好菜!!!', // 分享描述
                    link: LINK_URL+'/app_index?locationFlag=1&pid='+getCookie('APP_USER_ID'), // 分享链接
                    imgUrl: 'https://baonuotest.oss-cn-beijing.aliyuncs.com/bainuo/e8590187-75b0-4115-aaad-2155bb20be08.jpg', // 分享图标
                    success: function () {
                        // 用户确认分享后执行的回调函数
                        // alert("分享成功");
                    },
                    cancel: function () {
                        // 用户取消分享后执行的回调函数
                        // alert("取消分享");
                    }
                })

                wx.error(function (err_res) {
                    console.log("wx.error")
                    console.log(err_res)
                });
            });
        }else{
            alert(res.message);
            clickFlag = true;
        }
    }

})
### 微信公众号 JSSDK 开发教程 #### 获取 Access Token 为了使用微信JSSDK,在服务器端需要先获取`access_token`。这是调用微信接口的全局唯一票据,有效时间为7200秒。开发者需自行负责在服务端维护此令牌并实现缓存机制以提高效率[^3]。 ```java // Java示例代码用于获取 access_token String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; URL url = new URL(accessTokenUrl); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null){ response.append(line); } reader.close(); JSONObject jsonResponse = new JSONObject(response.toString()); String accessToken = jsonResponse.getString("access_token"); ``` #### 配置 JS SDK 接口签名 前端页面加载前,通过后台向微信公众平台发起请求获得配置所需的参数列表,包括但不限于`noncestr`, `timestamp`, 和 `signature`等字段。这些数据用来验证当前网页访问合法性以及防止跨站伪造攻击[^1]。 ```javascript wx.config({ debug: false, // 开启调试模式, 调用的所有 api 的返回值会在客户端 alert 出来,建议仅在测试环境开启 appId: 'your-app-id', // 必填,公众号的唯一标识 timestamp: res.timestamp, // 必填,生成签名的时间戳 nonceStr: res.nonceStr, // 必填,生成签名的随机串 signature: res.signature,// 必填,签名 jsApiList: ['getLocation'] // 必填,需要使用的JS接口列表 }); ``` #### 使用 JSSDK 功能 一旦完成上述准备工作之后就可以正常使用各种功能API了。比如这里展示了一个简单的例子——利用`getLocation()`方法取得用户的地理位置信息: ```html <button id="get-location">Get Location</button> <script src="//res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> <script type="text/javascript"> document.getElementById('get-location').onclick = function(){ wx.getLocation({ success:function(res){ console.log(`Latitude:${res.latitude}, Longitude:${res.longitude}`); }, cancel:function(){ console.error('User refused to provide location.'); } }); }; </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值