Springboot+redis调用微信扫码功能
1.登录微信公众号 注册订阅号 (其他 服务号和小程序,企业微信大多适用于企业也不好申请)注册时有些身份证号 和 人脸识别的验证
2. 进入公众号控制台 → 公众号设置 → 功能设置 ,添加域名 且 下载认证文件并 放到 要绑定的外网页面根目录下验证来绑
3.基本设置 拿到 AppID 和 AppSecret,并添加白名单 (这里需要配申城 acc_token的IP)
4.测试
生成ACCESS_TOKEN
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xxx&secret=xxx
根据ACCESS_TOKEN生成 jsapi_ticket (有效期7200秒)
https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
5.JS-SDK使用权限签名算法(官方给的就行)
逻辑:生成 ACCESS_TOKEN , 根据ACCESS_TOKEN生成 jsapi_ticket,将jsapi_ticket(生成令牌),nonceStr(UUID),timeStamp(当前时间戳),url(前台访问页面路径) 封装成json给前端
后台实现:
1. 调用类JsApiController
import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.hs.Constants; import com.hs.model.WXTokenModel; import com.hs.pojo.IMoocJSONResult; import com.hs.service.JsApiService; import com.hs.utils.RedisCacheUtil; import io.swagger.annotations.Api; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.query.Param; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @Api(tags = "微信模块API") @RestController @Slf4j @RequestMapping("/jsapi") public class JsApiController { @Autowired private JsApiService jsApiService; @Autowired private RedisCacheUtil redisCacheUtil; @GetMapping(value = "/getSign") @ResponseBody public MapgetSign(@Param("tokenUrl") String tokenUrl, HttpServletRequest request) { Map res = jsApiService.sign(tokenUrl); return res; } }
2.实现类JsApiServiceImpl
import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Formatter; import java.util.HashMap; import java.util.Map; import java.util.UUID; import com.alibaba.fastjson.JSONObject; import com.hs.Constants; import com.hs.enums.CacheObjectType; import com.hs.model.WXTokenModel; import com.hs.service.JsApiService; import com.hs.utils.HttpClientUtil; import com.hs.utils.RedisCacheUtil; import com.hs.utils.WechatUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional @Slf4j public class JsApiServiceImpl implements JsApiService { @Autowired private RedisCacheUtil redisCacheUtil; /** * 获取签名 * * @param url * @return */ public Mapsign(String url) { Map resultMap = new HashMap<>(16); //这里的jsapi_ticket是获取的jsapi_ticket。 String jsapiTicket = this.getJsApiTicket(); //这里签名中的nonceStr要与前端页面config中的nonceStr保持一致,所以这里获取并生成签名之后,还要将其原值传到前端 String nonceStr = createNonceStr(); //nonceStr String timestamp = createTimestamp(); String string1; String signature = ""; //注意这里参数名必须全部小写,且必须有序 string1 = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url; System.out.println("string1:" + 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(); } resultMap.put("url", url); resultMap.put("jsapi_ticket", jsapiTicket); resultMap.put("nonceStr", nonceStr); resultMap.put("timestamp", timestamp); resultMap.put("signature", signature); resultMap.put("appId", Constants.GZH_APPID); return resultMap; } 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 createNonceStr() { return UUID.randomUUID().toString(); } private static String createTimestamp() { return Long.toString(System.currentTimeMillis() / 1000); } public String getJsApiTicket() { CacheObjectType cacheObject = CacheObjectType.WX_TOKEN; String ticket = (String) redisCacheUtil.get(cacheObject.getPrefix() + "jsapi_ticket"); if (StringUtils.isBlank(ticket)) { ticket = WechatUtil.getJsApiTicket(getAccessToken()); redisCacheUtil.set(cacheObject.getPrefix() + "jsapi_ticket", ticket, cacheObject.getExpiredTime()); } return ticket; } @Override public WXTokenModel getWXResult() { String url = "https://api.weixin.qq.com/cgi-bin/token"; Map param = new HashMap<>(16); param.put("grant_type", "client_credential"); param.put("appid", Constants.GZH_APPID); param.put("secret", Constants.GZH_SECURET); String wxResult = HttpClientUtil.doGet(url, param); log.info("get Access_token : {}", wxResult); WXTokenModel model = JSONObject.parseObject(wxResult, WXTokenModel.class); return model; } /** * 获取token * * @return */ private String getAccessToken() { Object obj = redisCacheUtil.get(Constants.GZH_TOKEN); if (obj == null) { WXTokenModel model = getWXResult(); redisCacheUtil.set(Constants.GZH_TOKEN, model.getAccess_token(), Long.parseLong(model.getExpires_in())); return model.getAccess_token(); } return (String) obj; } private String getToken() { String token = (String) redisCacheUtil.get(Constants.GZH_TOKEN); return token; } }
3.微信工具类 WechatUtil
import com.alibaba.fastjson.JSONObject; import com.hs.Constants; import org.apache.commons.lang3.StringUtils; /** * 微信工具类 */ public class WechatUtil { /** * 获得jsapi_ticket */ public static String getJsApiTicket(String token) { String url = Constants.JSAPI_TICKET + "?access_token=" + token + "&type=jsapi"; String response = HttpClientUtil.doGet(url); // WXSessionModel model = JsonUtils.jsonToPojo(response, WXSessionModel.class); // String response = OkHttpUtil.doGet(url); if (StringUtils.isBlank(response)) { return null; } JSONObject jsonObject = JSONObject.parseObject(response); System.out.println(response); String ticket = jsonObject.getString("ticket"); return ticket; } }
4.配置类 Constants
public class Constants { //换取ticket的url public static final String JSAPI_TICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket"; //微信公众号token在redis中存储时的key值 public static final String GZH_TOKEN = "wxgzh-access-token"; //手动写死一下域名 public static final String AppDomain = "www.xxx.cloud"; public static final String GZH_APPID = "aaaaaaaa"; public static final String GZH_SECURET = "bbbbbbbbbbb"; }
5.HttpClient工具类
import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpClientUtil { public static String doGet(String url, Mapparam) { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGet(String url) { return doGet(url, null); } public static String doPost(String url, Map param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doPost(String url) { return doPost(url, null); } public static String doPostJson(String url, String json) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } }
6.redis工具类RedisCacheUtil
import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.geo.Circle; import org.springframework.data.geo.Distance; import org.springframework.data.geo.GeoResults; import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Point; import org.springframework.data.redis.connection.RedisGeoCommands; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; /** * @author gao.fx * @date 2018-11-08 */ @Component @Slf4j public class RedisCacheUtil { private static RedisCacheUtil redisCacheUtil; @Autowired private RedisTemplate redisTemplate; /** * 将当前对象赋值给静态对象,调用spring组件: redisCacheUtil.redisTemplate.xxx() */ @PostConstruct public void init() { redisCacheUtil = this; } /** * 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) * @return */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据key 获取过期时间 * * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 判断key是否存在 * * @param key 键 * @return true 存在 false不存在 */ public boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除缓存 * * @param key 可以传一个值 或多个 */ @SuppressWarnings("unchecked") public void del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(CollectionUtils.arrayToList(key)); } } } // ============================String============================= /** * 普通缓存获取 * * @param key 键 * @return 值 */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 普通缓存放入 * * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 普通缓存放入并设置时间 * * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 */ public boolean set(String key, Object value, long time) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 递增 * * @param key 键 * @param delta 要增加几(大于0) * @return */ public long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * * @param key 键 * @param delta 要减少几(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } // ================================Map================================= /** * HashGet * * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * * @param key 键 * @return 对应的多个键值 */ public Map
7.maven
<dependency> <groupId>org.apache.httpcomponentsgroupId> <artifactId>httpclientartifactId> <version>4.5.13version> dependency> <dependency> <groupId>org.apache.httpcomponentsgroupId> <artifactId>httpclient-cacheartifactId> <version>4.5.13version> dependency> <dependency> <groupId>org.apache.httpcomponentsgroupId> <artifactId>httpmimeartifactId> <version>4.5.13version> dependency>
转载:https://blog.csdn.net/FrenandoChiang/article/details/89311592
前台:
1.下载官方提供的 jweixin-1.2.0.js
2.调后台接口 返回 签名
3.封装全局变量 wx.config({
debug:true,// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: _appId,// 必填,公众号的唯一标识
timestamp: _timestamp,// 必填,生成签名的时间戳
nonceStr: _nonceStr,// 必填,生成签名的随机串
signature: _signature,// 必填,签名,见附录1
jsApiList: ['checkJsApi','scanQRCode']
// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
4.调用微信扫码