通过get请求获取专属海报
/**
* 获取专属海报
*
* @param mid 会议编号
* @param openId 邀请人唯一码
* @return
*/
@SneakyThrows
@ApiOperation(value = "获取专属海报", notes = "获取专属海报")
@RequestMapping(value = "/getOwnPoster")
public ModelAndView getOwnPoster(@RequestParam(value = "mid") String mid,
@RequestParam(value = "code", required = false) String code,
@RequestParam(value = "openId", required = false) String openId,
HttpServletRequest request, HttpServletResponse response) {
if (StringUtil.isEmpty(openId)) {
if (StringUtil.isNotEmpty(code)) {
LOGGER.info("开始调用TencentApi服务,code为:{}", code);
// 微信用户信息
String wxResult = tencentApiClient.getWxUserInfo(code);
LOGGER.info("调用微信接口返回信息:{}", wxResult);
if (ERROR_CODE.equals(wxResult)) {
ModelAndView modelAndView = new ModelAndView("html/error");
return modelAndView;
} else {
WxUserInfoVo wxUserInfoVo = JSON.parseObject(wxResult, WxUserInfoVo.class);
// 保存微信用户信息到裂变主表
wxFisssionService.saveWxUserInfoToMain(wxUserInfoVo, mid);
openId = wxUserInfoVo.getOpenid();
String url = "https://m.woyaoce.cn/special/act/getOwnPoster?mid=" + mid + "&openId=" + openId;
response.sendRedirect(url);
}
}
}
// 根据openid、mid获取一条唯一微信用户信息
List<WxFissionInnovation> wxUserInfos = wxFissionInnovationMapper.getUserInfoByOpenIdAndMid(openId, mid);
// 生成专属二维码
String url = "https://m.woyaoce.cn/special/act/getCode?mid=" + mid + "&aoid=" + openId;
LOGGER.info("我的专属海报地址是:{}" + url);
String qrcode = QRCodeUtil.creatRrCode(url, 200, 200);
ModelAndView modelAndView = new ModelAndView("wxfission/qr");
modelAndView.addObject("qrcode", qrcode);
if (wxUserInfos.get(0).getNickName().length() > 5) {
wxUserInfos.get(0).setNickName(wxUserInfos.get(0).getNickName().substring(0, 3) + "...");
}
modelAndView.addObject("wxUserInfo", wxUserInfos.get(0));
//微信分享
StringBuilder sb = new StringBuilder("https://m.woyaoce.cn/special/act/getOwnPoster");
Enumeration enu = request.getParameterNames();
//获取请求参数名信息
String key = "";
int a = 1;
while (enu.hasMoreElements()) {
key = (String) enu.nextElement();
//得到参数名
if (!"id".equals(key)) {
sb.append((a == 1 ? "?" : "&") + key + "=" + request.getParameter(key));
//获取参数值,同时进行拼装
a++;
}
}
String s = sb.toString();
WeiXinJsSdk weiXinJsSdk = new WeiXinJsSdk();
String encodeUrl = "";
try {
encodeUrl = URLEncoder.encode(s, "UTF-8");
String url1 = "http://Openapi.woyaoce.cn/WeiXinJsSdk/GetInsSdk?url=" + encodeUrl;
System.out.println(url1);
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("url", encodeUrl);
String ss = HttpXmlClient.httpGet("http://Openapi.woyaoce.cn/WeiXinJsSdk/GetInsSdk", map);
weiXinJsSdk = JsonUtils.toBean(ss, WeiXinJsSdk.class);
} catch (Exception e) {
e.printStackTrace();
}
weiXinJsSdk.setNowurl(s);
weiXinJsSdk.setSharetitle(wxUserInfos.get(0).getNickName() + "邀请您报名参加" + wxUserInfos.get(0).getMetName());
weiXinJsSdk.setSharcontent("");
String imgUrl = "https://img1.17img.cn/ui/simg/woyaoce/20180125/images/300_300wyc.jpg";
weiXinJsSdk.setSharimg(imgUrl);
modelAndView.addObject("weiXinJsSdk", weiXinJsSdk);
return modelAndView;
}
/**
* 微信公众号中点击获取专属海报链接
*
* @param mid 会议编号
* @param response
*/
@ApiOperation(value = "微信公众号中点击获取专属海报链接", notes = "微信公众号中点击获取专属海报链接")
@RequestMapping(value = "/getPosterForGzh")
public void getPosterForGzh(@RequestParam(value = "mid") String mid,
HttpServletResponse response) {
String redirectUri = "https://m.woyaoce.cn/special/act/getOwnPoster?mid=" + mid;
try {
redirectUri = URLEncoder.encode(redirectUri, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 微信授权接口
String getCodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" + WxConstants.APPID +
"&redirect_uri=" + redirectUri +
"&response_type=code&" +
"scope=snsapi_userinfo&" +
"state=STATE&connect_redirect=1#wechat_redirect";
try {
response.sendRedirect(getCodeUrl);
} catch (IOException e) {
e.printStackTrace();
LOGGER.error("错误信息为:", e);
}
}
生成专属二维码关键代码
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Hashtable;
public class QRCodeUtil {
public static String creatRrCode(String contents, int width, int height) {
String binary = null;
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(
contents, BarcodeFormat.QR_CODE, width, height, hints);
// 1、读取文件转换为字节数组
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedImage image = toBufferedImage(bitMatrix);
//转换成png格式的IO流
ImageIO.write(image, "png", out);
byte[] bytes = out.toByteArray();
// 2、将字节数组转为二进制
BASE64Encoder encoder = new BASE64Encoder();
binary = encoder.encodeBuffer(bytes).trim();
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return binary;
}
/**
* image流数据处理
*
* @author ianly
*/
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
return image;
}
// 使用以下main方法可以直接生成以下链接的专属二维码base64地址,赋值到浏览器上即可看到效果
public static void main(String[] args) {
String binary = creatRrCode("https://m.woyaoce.cn/special/act/getCode?mid=17657", 200,200);
System.out.println(binary);
}
}
前端代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<meta content="yes" name="apple-mobile-web-app-capable">
<meta content="black" name="apple-mobile-web-app-status-bar-style">
<meta content="telephone=no" name="format-detection">
<meta content="email=no" name="format-detection">
<meta name="description" content="不超过150个字符"/>
<meta name="keywords" content=""/>
<meta content="caibaojian" name="author"/>
<title th:text="${weiXinJsSdk.getSharetitle()}"></title>
<link rel="canonical" th:href="${'https://m.woyaoce.cn/special/act/getPosterForGzh?mid='+wxUserInfo.getMid()}">
<link rel="stylesheet" href="https://img1.17img.cn/ui/simg/woyaoce/jl/wap/base.css">
<link rel="stylesheet" href="/special/static/css/wx/style.css">
<script src="/special/static/js/html2canvas.js"></script>
<script src="https://m.woyaoce.cn/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
//引入该flexible.min.js
!function(e,t){function n(){var n=l.getBoundingClientRect().width;t=t||540,n>t&&(n=t);var i=100*n/e;r.innerHTML="html{font-size:"+i+"px;}"}var i,d=document,o=window,l=d.documentElement,r=document.createElement("style");if(l.firstElementChild)l.firstElementChild.appendChild(r);else{var a=d.createElement("div");a.appendChild(r),d.write(a.innerHTML),a=null}n(),o.addEventListener("resize",function(){clearTimeout(i),i=setTimeout(n,300)},!1),o.addEventListener("pageshow",function(e){e.persisted&&(clearTimeout(i),i=setTimeout(n,300))},!1),"complete"===d.readyState?d.body.style.fontSize="16px":d.addEventListener("DOMContentLoaded",function(e){d.body.style.fontSize="16px"},!1)}(750,750);
</script>
</head>
<body>
<div class="box" id="hidden_wrap" style="position: relative">
<div class="success-text" id="first" style="position: absolute;margin-left: 0.3rem">
<!--当前登录人openid-->
<input id="openId" th:value="${wxUserInfo.getOpenId()}" hidden="hidden"/>
<!--当前登录人mid-->
<input id="mid" th:value="${wxUserInfo.getMid()}" hidden="hidden"/>
<!--当前登录人mid-->
<input id="headImgUrl" th:value="${wxUserInfo.getHeadImgUrl()}" hidden="hidden"/>
<div class="avator center690 clearfix space-s-p-t">
<span class="avator-img fl sp"><img id="headImg" th:src="${wxUserInfo.getHeadImgUrl()}" style="position: absolute" crossorigin="anonymous"></span>
<span class="fl avator-text space-m-m-l space-s-m-t" style="width: 5.2rem">
<p class="space-s-m-t"><span class="f18 fw600 color-white ">我是[[${wxUserInfo.nickName}]],邀请您参会:</span></p>
<p class="space-s-m-t"><span class="f18 fw600 color-white pStyle" style="font-size: 15px">[[${wxUserInfo.metName}]]</span></p>
</span>
</div>
</div>
<div id="qrcode" class="tc typesetting-secondary f18 pa" style="bottom:0.4rem; right: 0.49rem;">
<img style="width:1.8rem;" th:src="'data:image/png;base64,'+${qrcode}" crossorigin="anonymous">
</div>
<!--专属海报背景图-->
<img id="back-img" src="https://img1.17img.cn/ui/simg/woyaoce/20210203/bg-lb.png">
</div>
<img style="width: 100%;height: auto;" class="o-img" id="o-img" src="" alt="" hidden>
<style>
.o-img{
position: absolute;
top: 0;
left: 0;
width: 100%;
z-index: 20;
}
.pStyle {
margin-top: .1rem;
margin-bottom: .1rem;
/*border: 1px solid #ccc;*/
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
</style>
</body>
<script>
<!--实现html转图片,进而实现长按分享-->
window.onload = function () {
html2canvas($("body"),{
useCORS:true, // 跨域
allowTaint:false, // 允许污染
async: false, // 是否异步解析和呈现元素
foreignObjectRendering: true,// 是否在浏览器支持的情况下使用ForeignObject渲染
dpi:300, // 清晰度
background: "#ffffff", // 背景色
onrendered:function(canvas){
$("#o-img").show();
const dataURL =canvas.toDataURL("image/png");
$("#o-img").attr("src",dataURL);
$("#back-img").hide();
}
})
}
</script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<!--定制微信专属分享链接-->
<script th:inline="javascript">
var shareimg = [[${weiXinJsSdk.sharimg}]];
var appid = [[${weiXinJsSdk.appId}]];
var newsdesc = [[${weiXinJsSdk.sharcontent}]];
var timestamp = [[${weiXinJsSdk.timestamp}]];
var nonceStr = [[${weiXinJsSdk.nonceStr}]];
var title = [[${weiXinJsSdk.sharetitle}]];
var link = [[${weiXinJsSdk.nowurl}]];
var signature = [[${weiXinJsSdk.signature}]];
console.log(link)
if (appid != null && appid != "") {
wx.config({
debug: false,
appId: appid,
timestamp: timestamp,
nonceStr: nonceStr,
signature: signature,
jsApiList: [
'onMenuShareAppMessage',
'onMenuShareTimeline',
'onMenuShareQQ',
'onMenuShareQZone',
]
});
wx.ready(function () {
wx.onMenuShareTimeline({
title: title,
link: link,
imgUrl: shareimg,
desc: newsdesc,
success: function () {
},
cancel: function () {
}
});
wx.onMenuShareAppMessage({
title: title,
imgUrl: shareimg,
link: link,
desc: newsdesc,
success: function () {
},
cancel: function () {
}
});
wx.onMenuShareQQ({
title: title,
imgUrl: shareimg,
link: link,
desc: newsdesc,
success: function () {
},
cancel: function () {
}
});
wx.onMenuShareQZone({
title: title,
imgUrl: shareimg,
link: link,
desc: newsdesc,
success: function () {
},
cancel: function () {
}
});
});
}
</script>
</html>