1. 程式人生 > 實用技巧 >php實現微信公眾號掃一掃

php實現微信公眾號掃一掃

環境介紹,這就不多說了

1,配置公眾號js安全域名

2,functios.php

<?php
define("appID", "你的appid");
define("appsecret", "你的appsecret");

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

3,index.php 複製以下程式碼

<?php
require_once("functions.php");
$jssdk=new JSSDK('你的appid','你的appsecret');
$signPackage = $jssdk->GetSignPackage();
?>
<html>
<head>
    <title>微信掃一掃</title>
    <meta charset="utf-8">
</head>
<body>
 <a href="javascript:;">
      掃一掃
</a>
</body>
</html>

<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script>
    wx.config({
        debug: false,
        appId: '<?php echo $signPackage["appId"];?>',
        timestamp: <?php echo $signPackage["timestamp"];?>,
        nonceStr: '<?php echo $signPackage["nonceStr"];?>',
        signature: '<?php echo $signPackage["signature"];?>',
        jsApiList: [
            // 所有要呼叫的 API 都要加到這個列表中
            "scanQRCode"
        ]
    });
    wx.ready(function () {
        // 在這裡呼叫 API
        $(document).on("click","a",function(){
            wx.scanQRCode({
                needResult: 1, // 預設為0,掃描結果由微信處理,1則直接返回掃描結果,
                scanType: ["qrCode","barCode"], // 可以指定掃二維碼還是一維碼,預設二者都有
                success: function (res) {
                    // alert(res.resultStr);
                    // window.location.href=res.resultStr;  //跳轉連結
                    for(i in res ){
                         //alert(i);           //獲得屬性
                        alert(i + "---" + res[i]);  //獲得屬性值
                    }
                    //var result = res.resultStr; // 當needResult 為 1 時,掃碼返回的結果
                    
                }
            });

        })
    });
</script>

4,第一次可能會提示沒有wp-token/jsapi_ticket.json檔案,你建立一個wp-token資料夾用來儲存jsapi_ticket和access_token就可以。如圖: