WeChat web development (10)--scan function interface

Contents of this article

1. Background

We can activate the scan function on the WeChat webpage, which can identify the content of one-dimensional codes and two-dimensional codes, and then implement our business logic according to the scan results.

2. Code

The code is as follows. It should be noted that the needResult parameter is best set to 1, that is, the result of scanning the code is processed by ourselves. If it is set to 0, wechat processing, it is difficult for us to customize the business logic to process the scan code result.

In addition, the result of scanning the code is stored in res.resultStr.

<input type="button" value="扫一扫" onclick="scan()"> |

	<script src="http://cdn.bootcdn.net/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
	<script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
	<script>
		var apiList = [ 'checkJsApi','scanQRCode' ];
		$(function() {
      
      
			// 向后端请求配置信息
			$.ajax({
      
      
				type : "GET",
				url : "/wx-server/wxJsapiSignature",
				data : {
      
      
					url : location.href.split('#')[0]
				},
				dataType : "json",
				success : function(res) {
      
      
					configInfo(res);
				}
			});
		});

		// 通过wx.config注入配置信息
		function configInfo(res) {
      
      
			wx.config({
      
      
				debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
				appId : res.appId, // 必填,公众号的唯一标识
				timestamp : res.timestamp, // 必填,生成签名的时间戳
				nonceStr : res.nonceStr, // 必填,生成签名的随机串
				signature : res.signature,// 必填,签名
				jsApiList : apiList
			// 必填,需要使用的JS接口列表
			});
			// 处理成功后回调
			wx.ready(function() {
      
      
				console.log("处理成功:");
				wx.checkJsApi({
      
      
					jsApiList : apiList,
					success : function(checkRes) {
      
      
						console.log("checkRes:", checkRes);
					}
				});
			});
			// 处理失败后回调
			wx.error(function(err) {
      
      
				console.log("处理失败:", err);
			});
		}
		// 扫一扫
		function scan() {
      
      
			wx.scanQRCode({
      
      
				needResult : 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
				scanType : [ "qrCode", "barCode" ], // 可以指定扫二维码还是一维码,默认二者都有
				success : function(res) {
      
      
					alert(res.resultStr);
				}
			});
		}
	</script>

3. Test

Using the WeChat client, click to scan, I made a QR code with the content of 1234, the scan result is as follows, it can be seen that the scan was successful.
insert image description here

Guess you like

Origin blog.csdn.net/woshisangsang/article/details/122836436