PHP调起微信扫一扫JS-SDK接口实现扫描二维码自动填写表单功能

 

 一、准备工作

  1. 绑定域名

先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。

设置与开发->公众号设置->功能设置->js安全域名

2.引入js文件

在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.6.0.js如需进一步提升服务稳定性,当上述资源不可访问时,可改访问:http://res2.wx.qq.com/open/js/jweixin-1.6.0.js (支持https)。

3.通过config接口注入权限验证配置

所有需要使用JS-SDK的页面必须先注入配置信息,否则将无法调用

wx.config({
  debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  appId: '', // 必填,公众号的唯一标识
  timestamp: , // 必填,生成签名的时间戳
  nonceStr: '', // 必填,生成签名的随机串
  signature: '',// 必填,签名
  jsApiList: [] // 必填,需要使用的JS接口列表
})

4.通过ready接口处理成功验证

wx.ready(function(){
  // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
});

5.通过error接口处理失败验证

wx.error(function(res){
  // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
});

6.公众号基本配置

配置服务器地址和令牌(Token),获取APPID和AppSecret

二、完整DEMO

sample.php

<?php
require_once("functions.php");
$jssdk=new JSSDK('YOURAPPID','YOURAPPpSECRET)');
$signPackage = $jssdk->GetSignPackage();
?>
<!DOCTYPE html>
<html lang="en">     
<meta  charset="utf-8" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
<head>
  <meta charset="UTF-8">
  <title></title>
  <style>
	  *{
		  margin: 0;
		  padding:0;
	  }
	.btn{
		    background-color: #4CAF50; /* Green */
		    border: none;
		    color: white;
		    /* padding: 15px 32px; */
		    text-align: center;
		    text-decoration: none;
		    display: inline-block;
		    font-size: 16px;
			border-radius: 12px;
			position: relative;
			top:  0%;
			width: 200px;
			height: 50px;
			font-size: 20px;

			
	}
	.div1{
		             width:100%;
		             height: 100%;
		             background: #ededed;
		             position: absolute;
					 text-align:center;
	}
	.div-form{
		width: 100%;
		height: 50%;
		align: center;
	}
  </style>
  <link rel="stylesheet" href="https://unpkg.com/layui@2.6.8/dist/css/layui.css">
</head>
<body>
<div class="div1">
 <div class="div-form">
  <div class="layui-form-item" style="padding-top: 50px;">
    <label class="layui-form-label">姓名</label>
    <div class="layui-input-block" style="width: 200px;">
      <input id="input1" type="text" name="title" required  lay-verify="required" placeholder="" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item" style="padding-top: 50px;">
    <label class="layui-form-label">工号</label>
    <div class="layui-input-block" style="width: 200px;">
      <input id="input2" type="text" name="title" required  lay-verify="required" placeholder="" autocomplete="off" class="layui-input">
    </div>
  </div>
  </div>
<button onclick="btn()" class="btn" id="btn1">点击扫一扫</button>
</div>
</body>
<script src="jquery.min.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

<script>
	
  /*
   * 注意:
   * 1. 所有的JS接口只能在公众号绑定的域名下调用,公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
   * 2. 如果发现在 Android 不能分享自定义内容,请到官网下载最新的包覆盖安装,Android 自定义分享接口需升级至 6.0.2.58 版本及以上。
   * 3. 常见问题及完整 JS-SDK 文档地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
   *
   * 开发中遇到问题详见文档“附录5-常见错误及解决办法”解决,如仍未能解决可通过以下渠道反馈:
   * 邮箱地址:weixin-open@qq.com
   * 邮件主题:【微信JS-SDK反馈】具体问题
   * 邮件内容说明:用简明的语言描述问题所在,并交代清楚遇到该问题的场景,可附上截屏图片,微信团队会尽快处理你的反馈。
   */
  wx.config({
    debug: true,
    appId: '<?php echo $signPackage["appId"];?>',
    timestamp: <?php echo $signPackage["timestamp"];?>,
    nonceStr: '<?php echo $signPackage["nonceStr"];?>',
    signature: '<?php echo $signPackage["signature"];?>',
    jsApiList: [ 'scanQRCode']
  });
  function btn(){
document.getElementById("btn1").innerHtml='重新扫描';
  wx.ready(function () {
   
            wx.scanQRCode({
                needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
                scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
                success: function (res) {
				var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
                var obj = JSON.parse(result);
					document.getElementById("input1").value=obj.name;
					document.getElementById("input2").value=obj.id;
                }
  })
})
};
</script>
</html>

functions.php

<?php
define("appID", "YOURAPPID");
define("appsecret", "YOURAPPSECRET");

class JSSDK {
    private $appId;
    private $appSecret;

    public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    public function getSignPackage() {
        $jsapiTicket =$this->getJsApiTicket();
        $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    private 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;
    }

    private function getJsApiTicket() {
        $data = json_decode(file_get_contents("wp-token/jsapi_ticket.json"));
        if ($data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen("wp-token/jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }

        return $ticket;
    }

    public function getAccessToken() {
        $data = json_decode(file_get_contents("wp-token/access_token.json"));
        if ($data->expire_time < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $fp = fopen("wp-token/access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
}
?>

三、结果演示

1.示例二维码

 2.在微信浏览器访问你的地址+sample.php点击扫一扫,扫描上方示例二维码,效果如下:

四、注意事项

TIPS:第一次打开可能会提示无法找到json文件,在根目录下建立wp-token文件夹用于存储access_token.json和jsapi_ticket.json文件。

1.官方文档地址:JS-SDK说明文档

2.官方DEMO体验及下载地址:DEMO页面和示例代码

3.常见错误及解决办法:常见错误及解决方法

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值