Wx生成二维码

1.配置yml application.yml

wx:open:# 微信开放平台 appidappid: wxed9954c01bb89b47# 微信开放平台 appsecretappsecret: a7482517235173ddb4083788de60b90e# 微信开放平台 重定向url(guli.shop需要在微信开放平台配置)redirecturl: http://guli.shop/api/ucenter/wx/callback

2.utils–>HttpClientUtils 生成二维码的工具类

/***  依赖的jar包有:commons-lang-2.6.jar、httpclient-4.3.2.jar、httpcore-4.3.1.jar、commons-io-2.4.jar* @author zhaoyb* 微信*/
public class HttpClientUtils {public static final int connTimeout=10000;public static final int readTimeout=10000;public static final String charset="UTF-8";private static HttpClient client = null;static {PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();cm.setMaxTotal(128);cm.setDefaultMaxPerRoute(128);client = HttpClients.custom().setConnectionManager(cm).build();}public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);}public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);}public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,SocketTimeoutException, Exception {return postForm(url, params, null, connTimeout, readTimeout);}public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,SocketTimeoutException, Exception {return postForm(url, params, null, connTimeout, readTimeout);}public static String get(String url) throws Exception {return get(url, charset, null, null);}public static String get(String url, String charset) throws Exception {return get(url, charset, connTimeout, readTimeout);}/*** 发送一个 Post 请求, 使用指定的字符集编码.** @param url* @param body RequestBody* @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3* @param charset 编码* @param connTimeout 建立链接超时时间,毫秒.* @param readTimeout 响应超时时间,毫秒.* @return ResponseBody, 使用指定的字符集编码.* @throws ConnectTimeoutException 建立链接超时异常* @throws SocketTimeoutException  响应超时* @throws Exception*/public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)throws ConnectTimeoutException, SocketTimeoutException, Exception {HttpClient client = null;HttpPost post = new HttpPost(url);String result = "";try {if (StringUtils.isNotBlank(body)) {HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));post.setEntity(entity);}// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}post.setConfig(customReqConf.build());HttpResponse res;if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(post);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(post);}result = IOUtils.toString(res.getEntity().getContent(), charset);} finally {post.releaseConnection();if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}return result;}/*** 提交form表单** @param url* @param params* @param connTimeout* @param readTimeout* @return* @throws ConnectTimeoutException* @throws SocketTimeoutException* @throws Exception*/public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,SocketTimeoutException, Exception {HttpClient client = null;HttpPost post = new HttpPost(url);try {if (params != null && !params.isEmpty()) {List<NameValuePair> formParams = new ArrayList<NameValuePair>();Set<Entry<String, String>> entrySet = params.entrySet();for (Entry<String, String> entry : entrySet) {formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);post.setEntity(entity);}if (headers != null && !headers.isEmpty()) {for (Entry<String, String> entry : headers.entrySet()) {post.addHeader(entry.getKey(), entry.getValue());}}// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}post.setConfig(customReqConf.build());HttpResponse res = null;if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(post);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(post);}return IOUtils.toString(res.getEntity().getContent(), "UTF-8");} finally {post.releaseConnection();if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}}/*** 发送一个 GET 请求** @param url* @param charset* @param connTimeout  建立链接超时时间,毫秒.* @param readTimeout  响应超时时间,毫秒.* @return* @throws ConnectTimeoutException   建立链接超时* @throws SocketTimeoutException   响应超时* @throws Exception*/public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)throws ConnectTimeoutException,SocketTimeoutException, Exception {HttpClient client = null;HttpGet get = new HttpGet(url);String result = "";try {// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}get.setConfig(customReqConf.build());HttpResponse res = null;if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(get);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(get);}result = IOUtils.toString(res.getEntity().getContent(), charset);} finally {get.releaseConnection();if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}return result;}/*** 从 response 里获取 charset** @param ressponse* @return*/@SuppressWarnings("unused")private static String getCharsetFromResponse(HttpResponse ressponse) {// Content-Type:text/html; charset=GBKif (ressponse.getEntity() != null  && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {String contentType = ressponse.getEntity().getContentType().getValue();if (contentType.contains("charset=")) {return contentType.substring(contentType.indexOf("charset=") + 8);}}return null;}/*** 创建 SSL连接* @return* @throws GeneralSecurityException*/private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {@Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;}@Overridepublic void verify(String host, SSLSocket ssl)throws IOException {}@Overridepublic void verify(String host, X509Certificate cert)throws SSLException {}@Overridepublic void verify(String host, String[] cns,String[] subjectAlts) throws SSLException {}});return HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (GeneralSecurityException e) {throw e;}}public static void main(String[] args) {try {String str= post("https://localhost:443/ssl/test.shtml","name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000);//String str= get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK");/*Map<String,String> map = new HashMap<String,String>();map.put("name", "111");map.put("page", "222");String str= postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);*/System.out.println(str);} catch (ConnectTimeoutException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SocketTimeoutException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

3.controller—>WxController @Api(tags=“微信登录与注册管理接口”)

@Controller
@RequestMapping("/api/ucenter/wx")
@Api(tags="微信登录与注册管理接口")
public class WxController {@Autowiredprivate UcenterMemberService ucenterMemberService;@Value("${wx.open.appid}")private String appid; //商家的id@Value("${wx.open.redirecturl}")private String redirectUri; //重定向的地址。@Value("${wx.open.appsecret}")private String appsecret; //商家密钥//确认登陆之后,获取用户的详细信息注册到数据库中,并登录@ApiOperation(value = "微信扫码注册并登录")@GetMapping("callback")public String callback(String code,String state){//1.得到access_token的值String uri1="https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";uri1=String.format(uri1,appid,appsecret,code); //获取acess_token  借助httpclient://TOdo: 如何通过java代码 把改地址进行请求发送? httpclient: 可以模拟浏览器转发地址,因为要获取acess_token,能用redirect,下边只是获取了二维码try {String access_token_result = HttpClientUtils.get(uri1);JSONObject jsonObject = JSON.parseObject(access_token_result);String access_token=jsonObject.getString("access_token");String openId=jsonObject.getString("openid");System.out.println(access_token+"~~~~~~~~access_token展示");//4.根据用户openid 判断数据库中是否存在UcenterMember member = this.ucenterMemberService.getOne(new QueryWrapper<UcenterMember>().eq("openid", openId));if (member==null){//根据你的access_token获取用户的信息String uri2 = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";uri2 = String.format(uri2, access_token, openId);String userinfo_result = HttpClientUtils.get(uri2);JSONObject jsonObject1 = JSON.parseObject(userinfo_result);System.out.println(jsonObject1+"~~~~~~~~~~~~jsonObject1");//3.把获取到的用户信息保存到数据库中member = new UcenterMember();member.setOpenid(jsonObject1.getString("openid"));member.setNickname(jsonObject1.getString("nickname"));member.setSex(jsonObject1.getInteger("sex"));member.setAvatar(jsonObject1.getString("headimgurl"));ucenterMemberService.save(member);}String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());System.out.println(jwtToken+"===============jwtToken");return "redirect:http://localhost:3000?token="+jwtToken;} catch (Exception e) {e.printStackTrace();}//state == lee 如何发生改变则---->被攻击伪造
//        System.out.println("-------"+code+"~~~~~~~"+state);return "";}//产生微信登录的二维码@ApiOperation(value = "生成微信登录的二维码")@GetMapping("/getWxCode")public String getWxCode(){//微信开放平台授权baseUrl 的地址String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +"?appid=%s" +"&redirect_uri=%s" +"&response_type=code" +"&scope=snsapi_login" +"&state=%s" +"#wechat_redirect";//请使用urlEncode 対链接进行处理//todo: 占位符(%s --- ?)的形式进行赋值try{redirectUri= URLEncoder.encode(redirectUri,"utf-8");}catch (UnsupportedEncodingException e){e.printStackTrace();}String resultUrl =  String.format(baseUrl, appid, redirectUri, "lee");//为baseUrl中%s赋值return "redirect:"+resultUrl; //重定向}
}

Wx腾讯 微信生成二维码--->微信扫描后注册并登录相关推荐

  1. Java生成二维码,扫描后跳转到指定的网站

    转自:https://suko.iteye.com/blog/2244138 本例我是应用google的二维码工具包来做的,附近提供jar包下载.下面是完整代码,经过测试的. jar下载路径:http ...

  2. java生成二维码、扫描后跳转到指定的页面或读取指定内容

    1.生成二维码需要导入的jar包 //spring boot 的maven项目 导入响应jar包<!-- 生成二维码 --><dependency><groupId> ...

  3. 二维码(生成二维码和扫描二维码)超简单 超简易

    二维码(生成二维码和扫描二维码)Zxing 例: 配置权限: 项目下的 build.gradle 文件里加入,7.0版本以后可能会转入settings.gradle文件 pluginManagemen ...

  4. 生成二维码,扫描二维码,二维码预览三件套。uQRCode、uni.scanCode、uni.previewImage

    生成二维码,扫描二维码,二维码预览三件套.uQRCode.uni.scanCode.uni.previewImage 一.生成二维码 使用插件:uQRCode(在uniapp插件市场下载引入) 将uq ...

  5. (转)ZXing生成二维码和带logo的二维码,模仿微信生成二维码效果

    场景:移动支付需要对二维码的生成与部署有所了解,掌握目前主流的二维码生成技术. 1 ZXing 生成二维码 首先说下,QRCode是日本人开发的,ZXing是google开发,barcode4j也是老 ...

  6. 微信小程序文字链接生成二维码,扫描识别二维码

    给大家推荐一个非常实用且有趣的微信小程序:超实用工具箱. 超实用工具箱小程序里面包含了很多小工具,涵盖了工作.日常生活和娱乐版块.具体的功能大家可以打开微信扫描下方二维码,即刻体验: 接下来给大家介绍 ...

  7. 使用 canvas 模拟微信生成二维码名片

    需求说明 模拟微信的二维码名片的功能 接口获取到用户的二维码,前端将二维码,背景图,用户头像(圆形),用户姓名等信息结合生成一张图片 示例 等比例创建画布 获取背景图,监听图片的 onload 事件 ...

  8. qrcode生成二维码微信长按无法识别问题

    最近用QRCode.js 生成二维码之后,发现在小米和华为手机的微信上面页面长按识别不了,苹果和其他手机浏览器是正常的.qrcode在页面生成会生成一个canvas标签和一个img标签,在电脑浏览器上 ...

  9. ZXing生成二维码和带logo的二维码,模仿微信生成二维码效果

    首先说下,QRCode是日本人开发的,ZXing是google开发,barcode4j也是老美开发的,barcode4j对一维条形码处理的很好,而且支持的格式很多,当然也可以对二维码进行处理,效果个人 ...

最新文章

  1. 百度地图API : 修改marker图标(icon)
  2. 1 数列分块入门_怎样用通俗易懂的语言让小学 OIer 理解并能初步运用线段树?...
  3. python的隐藏功能分享_【图片】分享一段功能非常简陋的python代码实现下载free种【pt吧】_百度贴吧...
  4. canvasnest 移动距离_GitHub - XiaoxinJiang/canvas-nest: 仿知乎登录页面canvas-nest
  5. Sublime Text 3 注册码失效(被移除)解决方法
  6. 将本地文件push到gitee上面
  7. linux kernel 本地提权漏洞CVE-2013-1763 exploit 代码分析
  8. 淘宝商城事件:中小卖家缺失的互联网信任
  9. awz3格式转epub格式转mobi格式
  10. pip install清华镜像源
  11. 再谈过时且脆弱的TCP长肥管道三宗罪!
  12. 将多个excel表合并到一个excel表
  13. webworker应用场景_多线程编程开发应用场景
  14. SOA RPC SOAP REST
  15. Oracle项目管理主数据之RBS与ROBS
  16. 字节跳动Web Infra发起 Modern.js 开源项目,打造现代 Web 工程体系
  17. php empty w3school,w3school的PHP教程提炼(一)PHP基础
  18. 找规律/数位DP HDOJ 4722 Good Numbers
  19. 什么是质押池,如何进行质押呢?
  20. 用VISIO2013绘制E-R图

热门文章

  1. 优效文件助手-【深度】都2021年了,你还只会用文件夹管理电脑文件?
  2. DHU 25繁殖问题
  3. android MVC,MVP,MVVM
  4. 《痞子衡嵌入式半月刊》 第 26 期
  5. 老虎证券赴美IPO:3年交易破万亿,5年9轮融资“众星捧月”...
  6. 使用 fmod windows 下实现音频变声 -- 萝莉 大叔 等 特效
  7. 使用01字典树解决最大异或问题
  8. 流利阅读 2019.3.5 Your friends’ social media posts are making you spend more money, researchers say
  9. c语言程序设计之基础题
  10. win7 MW300U 共享wifi