调用微信扫一扫需要使用微信公众号(订阅号也可以)自带的微信扫一扫功能
公众号配置
首先配置js接口安全域名
然后找到appid和secret 备用
然后代码,PHP文件(填入appid和secret)
public function index () {
$Config = $this->getConfig();
$this->assign("Config", $Config);
return view();
}
public function getConfig(){
// 微信 JS 接口签名校验工具: https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
$appid = 'wxb9b9*****07df';
$secret = 'e503***************4845c86';
// 获取token
$token=$this->get_token($appid,$secret);
// 获取ticket
$ticket=$this->get_ticket($token);
// 进行sha1签名
$timestamp = time();
$nonceStr = $this->createNonceStr();
// 注意 URL 建议动态获取(也可以写死).
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; // 调用JSSDK的页面地址
// $url = $_SERVER['HTTP_REFERER']; // 前后端分离的, 获取请求地址(此值不准确时可以通过其他方式解决)
$str = "jsapi_ticket={$ticket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}";
$sha_str = sha1($str);
return ['appid'=>$appid,'timestamp'=>$timestamp,'nonceStr'=>$nonceStr,'sha_str'=>$sha_str];
}
function get_token($appid,$secret){
$token_data = @file_get_contents('wechat_token.txt');
if (!empty($token_data)) {
$token_data = json_decode($token_data, true);
$time = time() - $token_data['time'];
if ($time > 3600) {
$token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
$token_res = $this->https_request($token_url);
$token_res = json_decode($token_res, true);
$token = $token_res['access_token'];
$data = array(
'time' =>time(),
'token' =>$token
);
file_put_contents('wechat_token.txt', json_encode($data));
} else {
$token = $token_data['token'];
}
}else{
$token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
$token_res = $this->https_request($token_url);
$token_res = json_decode($token_res, true);
$token = $token_res['access_token'];
$data = array(
'time' =>time(),
'token' =>$token
);
file_put_contents('wechat_token.txt', json_encode($data));
}
return $token;
}
function get_ticket($token){
$ticket_data = @file_get_contents('wechat_ticket.txt');
if (!empty($ticket_data)) {
$ticket_data = json_decode($ticket_data, true);
$time = time() - $ticket_data['time'];
if ($time > 3600) {
$ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi";
$ticket_res = $this->https_request($ticket_url);
$ticket_res = json_decode($ticket_res, true);
$ticket = $ticket_res['ticket'];
$data = array(
'time' =>time(),
'ticket' =>$ticket
);
file_put_contents('wechat_ticket.txt', json_encode($data));
} else {
$ticket = $ticket_data['ticket'];
}
}else{
$ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi";
$ticket_res = $this->https_request($ticket_url);
$ticket_res = json_decode($ticket_res, true);
$ticket = $ticket_res['ticket'];
$data = array(
'time' =>time(),
'ticket' =>$ticket
);
file_put_contents('wechat_ticket.txt', json_encode($data));
}
return $ticket;
}
function createNonceStr($length = 16) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
/**
* 模拟 http 请求
* @param String $url 请求网址
* @param Array $data 数据
*/
function https_request($url, $data = null){
// curl 初始化
$curl = curl_init();
// curl 设置
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
// 判断 $data get or post
if ( !empty($data) ) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// 执行
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
然后html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>test</title>
<script src="js/jquery-3.3.1.min.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<style>a:hover{text-decoration: none;}</style>
</head>
<body>
<button id="scanQRCode">扫码</button>
<text id="code"></text>
</body>
<script>
$(function(){
wx.config({
// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
debug: false,
// 必填,公众号的唯一标识
appId: "{$Config['appid']}",
// 必填,生成签名的时间戳
timestamp:""+"{$Config['timestamp']}",
// 必填,生成签名的随机串
nonceStr:"{$Config['nonceStr']}",
// 必填,签名,见附录1
signature:"{$Config['sha_str']}",
// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
jsApiList : [ 'checkJsApi', 'scanQRCode' ]
});
wx.error(function(res) {
alert("出错了:" + res.errMsg);//这个地方的好处就是wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。
});
wx.ready(function() {
wx.checkJsApi({
jsApiList : ['scanQRCode'],
success : function(res) {
}
});
//点击按钮扫描二维码
document.querySelector('#scanQRCode').onclick = function() {
wx.scanQRCode({
needResult : 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType : ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success : function(res) {
alert(res.resultStr);//二维码信息
var result=res.resultStr.split(",");//条形码信息
$('#code').html(result[1]);
}
});
};
});
})
</script>
</html>