# wx-sign
**Repository Path**: liuze/wx-sign
## Basic Information
- **Project Name**: wx-sign
- **Description**: Java微信公众号JS-SDK生成签名接口
- **Primary Language**: Java
- **License**: Apache-2.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 10
- **Created**: 2019-06-25
- **Last Updated**: 2020-12-18
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# wx-sign
## 项目介绍
Java微信公众号JS-SDK生成签名接口,使用SpringBoot开发,支持跨域,支持独立部署,不需要数据库,
用IDEA导入项目后可以直接启动。
## 使用方法
**第一步 在微信公众号“开发/基本配置”里面配置IP白名单;**
用浏览器访问`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xxx&secret=xxx`,
微信会提示出你电脑的ip,url里面的`appid`和`secret`换成你自己公众号的。
或者直接访问`http://www.ip138.com/`即可获取到你电脑的外网ip。
**第二步 前端页面里面调用接口获取签名**:
```javascript
$.get('http://localhost:8083/api/getJSSDKSignature', {
appId: appId, // 公众号id
secret: appSecret, // 公众号密钥
url: location.href // 当前页面url
}, function (res) {
if (200 == res.code) {
wx.config({
debug: true, // 开启调试模式
appId: appId, // 公众号id
timestamp: res.timestamp, // 生成签名的时间戳
nonceStr: res.nonceStr, // 生成签名的随机串
signature: res.signature,// 签名
jsApiList: ['scanQRCode', 'getLocation', 'openLocation'] // 需要使用的JS接口列表
});
} else {
alert(res.msg);
}
});
wx.ready(function () {
});
wx.error(function (res) {
alert(JSON.stringify(res));
});
```
## 源码解读:
```java
@RequestMapping("/api")
@RestController
public class ApiController {
// 获取微信JS-SDK签名
@RequestMapping("/getJSSDKSignature")
public JsonResult getJSSDKSignature(String appId, String secret, String url) {
String tokenJson = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret, null);
String access_token = JSONUtil.getString(tokenJson, "access_token"); // access_token
String ticketJson = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi", null);
String ticket = JSONUtil.getString(ticketJson, "ticket"); // ticket
String noncestr = UUIDUtil.randomUUID8(); // 随机字符串
long timestamp = new Date().getTime(); // 时间戳
String str = "jsapi_ticket=" + ticket;
str += "&noncestr=" + noncestr;
str += "×tamp=" + timestamp;
str += "&url=" + url;
String signature = DigestUtils.sha1Hex(str);
return JsonResult.ok().put("timestamp", timestamp).put("nonceStr", noncestr).put("signature", signature);
}
}
```
返回给前端的json示例:
```json
{
"code": 200,
"msg": "操作成功",
"timestamp": 1544753553997,
"nonceStr": "SuM0XA6e",
"signature": "5069314375e2d5cd1836bf8051ee6b825d53960c"
}
```
> 可以部署在自己服务器上面同时给多个项目使用。
## 推荐
[EasyWeb管理系统模板](http://easyweb.vip) |
[基于OAuth2.0的前后端分离开发平台](https://gitee.com/whvse/EasyWeb)