天天看點

php微信jssdk配置

包括緩存,包括https通訊,擷取微信access_token,簽名什麼的都有。但是防範性程式設計做得比較少,商業用的話,需要完善下代碼。

關注我的微信公衆号【前端基礎教程從0開始】,加我微信,可以免費為您解答問題。回複“1”,拉你程序式員技術讨論群。回複“小程式”,領取300個優秀的小程式開源代碼+一套入門教程。回複“領取資源”,領取300G前端,Java,微信小程式,Python等資源,讓我們一起學前端。

前端使用方式:

ajax(Common.ServerUrl + "GetWX.php", {
    data: {
            Type: "config", url: location.href.split('#')[0]
    },
    dataType: 'json',
    type: 'get',
    timeout: 5000,
    success: function(data) {
        wx.config({
            debug: true, // 開啟調試模式,調用的所有api的傳回值會在用戶端alert出來,若要檢視傳入的參數,可以在pc端打開,參數資訊會通過log打出,僅在pc端時才會列印。
            appId: '……', // 必填,公衆号的唯一辨別
            timestamp: data.timestamp, // 必填,生成簽名的時間戳
            nonceStr: data.nonceStr, // 必填,生成簽名的随機串
            signature: data.signature, // 必填,簽名,見附錄1
            jsApiList: ["getLocation"] // 必填,需要使用的JS接口清單,所有JS接口清單見附錄2
            });
    }
});

wx.ready(function() {
    wx.getLocation({
        type: 'wgs84', // 預設為wgs84的gps坐标,如果要傳回直接給openLocation用的火星坐标,可傳入'gcj02'
        success: function(res) {
            var latitude = res.latitude; // 緯度,浮點數,範圍為90 ~ -90
            var longitude = res.longitude; // 經度,浮點數,範圍為180 ~ -180。
            plus2.storage.setItem("latitude", latitude);
            plus2.storage.setItem("longitude", longitude);
        }
    });
});
           

PHP配置:

<?php
    include "Cache.php";
    define($APPID, "……");
    define($SECRET, "……");
    if($_GET['Type'] == "access_token"){
//      echo getAccess_token();
    }
    else if($_GET['Type'] == "jsapi_ticket"){
//      echo getJsapi_ticket();
    }
    else if($_GET['Type'] == "config"){
        $jsapi_ticket = getJsapi_ticket();
        $nonceStr = "x".rand(10000,100000)."x";    //随機字元串
        $timestamp = time();   //時間戳
        $url = $_GET['url'];
        $signature = getSignature($jsapi_ticket,$nonceStr, $timestamp, $url);

        $result = array("jsapi_ticket"=>$jsapi_ticket, "nonceStr"=>$nonceStr,"timestamp"=>$timestamp,"url"=>$url,"signature"=>$signature);
        echo json_encode($result);
    }

    function getSignature($jsapi_ticket,$noncestr, $timestamp, $url){
        $string1 = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$noncestr."&timestamp=".$timestamp."&url=".$url;
        $sha1 = sha1($string1);
        return $sha1;
    }
    function getJsapi_ticket(){
        $cache = new Cache();
        $cache = new Cache(7000, 'cache/');    //需要建立cache檔案夾存儲緩存檔案。
        //從緩存從讀取鍵值 $key 的資料
        $jsapi_ticket = $cache -> get("jsapi_ticket");
        $access_token = getAccess_token();
        //如果沒有緩存資料
        if ($jsapi_ticket == false) {
            $access_token = getAccess_token();
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
            $data = array('type'=>'jsapi','access_token'=>$access_token);
            $header = array();
            $response = json_decode(curl_https($url, $data, $header, 5));
            $jsapi_ticket = $response->ticket;
            //寫入鍵值 $key 的資料
            $cache -> put("jsapi_ticket", $jsapi_ticket);
        }
        return $jsapi_ticket;
    }
    function getAccess_token(){
        $cache = new Cache();
        $cache = new Cache(7000, 'cache/');
        //從緩存從讀取鍵值 $key 的資料
        $access_token = $cache -> get("access_token");

        //如果沒有緩存資料
        if ($access_token == false) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token';
            $data = array('grant_type'=>'client_credential','appid'=>$APPID,'secret'=>$SECRET);
            $header = array();

            $response = json_decode(curl_https($url, $data, $header, 5));
            $access_token = $response->access_token;
            //寫入鍵值 $key 的資料
            $cache -> put("access_token", $access_token);
        }
        return $access_token;
    }

    /** curl 擷取 https 請求
     * @param String $url 請求的url
     * @param Array $data 要發送的數據
     * @param Array $header 請求時發送的header
     * @param int $timeout 逾時時間,預設30s
     */

    function curl_https($url, $data=array(), $header=array(), $timeout=30){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳過證書檢查
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

        $response = curl_exec($ch);

        if($error=curl_error($ch)){
            die($error);
        }

        curl_close($ch);

        return $response;

    }
           

緩存檔案:

<?php
class Cache {
    private $cache_path;
    //path for the cache
    private $cache_expire;
    //seconds that the cache expires

    //cache constructor, optional expiring time and cache path
    public function Cache($exp_time = 3600, $path = "cache/") {
        $this -> cache_expire = $exp_time;
        $this -> cache_path = $path;
    }

    //returns the filename for the cache
    private function fileName($key) {
        return $this -> cache_path . md5($key);
    }

    //creates new cache files with the given data, $key== name of the cache, data the info/values to store
    public function put($key, $data) {
        $values = serialize($data);
        $filename = $this -> fileName($key);
        $file = fopen($filename, 'w');
        if ($file) {//able to create the file
            fwrite($file, $values);
            fclose($file);
        } else
            return false;
    }
    //returns cache for the given key
    public function get($key) {
        $filename = $this -> fileName($key);
        if (!file_exists($filename) || !is_readable($filename)) {//can't read the cache
            return false;
        }
        if (time() < (filemtime($filename) + $this -> cache_expire)) {//cache for the key not expired
            $file = fopen($filename, "r");
            // read data file
            if ($file) {//able to open the file
                $data = fread($file, filesize($filename));
                fclose($file);
                return unserialize($data);
                //return the values
            } else
                return false;
        } else
            return false;
        //was expired you need to create new
    }

}
           

繼續閱讀