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<String, Object> resultMap = new HashMap<String, Object>();
	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<String,String> 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 + "&timestamp=" + timestamp + "&url=" + urlInfo;

			//6、将字符串进行sha1加密
			String signature = SHA1Util.SHA1(str);
			map = new HashMap<String,String>();
			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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wengelovelian

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值