H5调起微信扫一扫

uni-app:

import jWeixin from 'jweixin-module';


let allowUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WXappid}&redirect_uri=${encodeURIComponent(WXredirectUrl)}&response_type=code&scope=${WXscope}&state=STATE#wechat_redirect`;

window.location.replace(allowUrl);

wxGetTicketInfo({urlInfo: location.href.split('#')[0]}).then(res=>{
    jWeixin.config({
	    debug: false, 
	    appId: res.data.appid, // 必填,公众号的唯一标识
	    timestamp: res.data.timestamp, // 必填,生成签名的时间戳
	    nonceStr: res.data.noncestr, // 必填,生成签名的随机串
        signature: res.data.signature,// 必填,签名
	    jsApiList: this.jsApiList // 必填,需要使用的JS接口列表
    });
})


jWeixin.scanQRCode({
	needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
	scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
	success: function (res) {
						
	},
	fail: function(err){
		// console.log('扫描失败:',err);
		uni.showModal({
			title:'温馨提示',
			content:'扫描失败,请重新扫码',
			showCancel:false,
			confirmText:'我知道了'
		})
	}
});

后端接口:


@RequestMapping("/login")
public void login(HttpServletResponse response) throws IOException {
	int type = weChatScan.getType();
    String redirect_uri = "http://xxx.xxx.xxx.xxx/api/scan/wxCallBackInfo"
	//请求地址
	String url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
			"?appid=" + appid +
			"&redirect_uri=" + URLEncoder.encode(redirect_uri, "UTF-8") +
			"&response_type=code" +
			"&scope=" + baseScope +
			"&state=STATE#wechat_redirect";
	//重定向
	String s = HttpUtil.get(url);
	response.sendRedirect(url);
}

// 回调方法
@GetMapping("/wxCallBackInfo")
public void wxCallBackInfo(WeChatScanDto weChatScan, HttpServletResponse response, @RequestParam("code") String code) {
	Map resultMap = new HashMap();
	String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
			"?appid=" + appid +
			"&secret=" + appsecret +
			"&code=" + code +
			"&grant_type=" + grant_type;
	try {
		String s = HttpUtil.get(url);
		//返回结果的json对象
		JSONObject resultObject = JSON.parseObject(s);
		String openid = resultObject.getString("openid");
		response.sendRedirect(scan_url + "?openId=" + openid);
	} catch (Exception e) {
		String message = e.getMessage();
		AesException aesException = new AesException(AesException.NoBindBuffer);
		if (!aesException.getMessage().equals(message)) {
			message = "微信扫码失败,请联系管理员!";
		}
	}
}

//获取前端所需的ticket
@GetMapping("/wxGetTicketInfo")
public AjaxResult wxLogin(HttpServletRequest request, String urlInfo) {
	WxConfig wxConfig = SpringUtils.getBean(WxConfig.class);
	String accessToken = redisCache.getCacheObject("wx_access_token");
	if(StringUtils.isEmpty(accessToken)){
		new WxUtil().createWxAccessToken();
		accessToken = redisCache.getCacheObject("wx_access_token");
	}
	String ticket = redisCache.getCacheObject("wx_ticket");
	Map map = redisCache.getCacheObject("wx_signature_map");
	if(StringUtils.isEmpty(ticket)){
		String ticketUrl = wxConfig.getTicket_url() + "?access_token=" + accessToken + "&type=jsapi";
		try{
			String ticketInfo = HttpUtil.get(ticketUrl);
			JSONObject ticketObject = JSON.parseObject(ticketInfo);
			String errcode = ticketObject.getString("errcode");
			if (!"0".equals(errcode)) {
				logger.info(ticketObject.toString());
				new WxUtil().createWxAccessToken();
				accessToken = redisCache.getCacheObject("wx_access_token");
				ticketUrl = wxConfig.getTicket_url() + "?access_token=" + accessToken + "&type=jsapi";
				ticketInfo = HttpUtil.get(ticketUrl);
				ticketObject = JSON.parseObject(ticketInfo);
			}
			logger.info(ticketObject.toString());
			ticket = ticketObject.getString("ticket");
			Integer ticketExpiresIn = ticketObject.getInteger("expires_in");
			redisCache.setCacheObject("wx_ticket", ticket, ticketExpiresIn, TimeUnit.SECONDS);
			String noncestr = SHA1Util.randomUUID();//随机字符串
			String timestamp = String.valueOf(System.currentTimeMillis()/1000);//时间戳
			//4获取url
			// 根据项目需要获取对应的url地址

			//5、将参数排序并拼接字符串
			String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + urlInfo;

			//6、将字符串进行sha1加密
			String signature = SHA1Util.SHA1(str);
			map = new HashMap();
			map.put("urlInfo", urlInfo);
			map.put("timestamp", timestamp);
			map.put("ticket", ticketObject.getString("ticket"));
			map.put("noncestr", noncestr);
			map.put("signature", signature);
			map.put("appid", wxConfig.getAppid());
			redisCache.setCacheObject("wx_signature_map", map);
		}catch (Exception e){
			logger.error("失败", e);
			return AjaxResult.error("获取签名失败");
		}
	}
	return AjaxResult.success(map);
}

你可能感兴趣的:(微信,前端)