讀古今文學網 > 微信公眾平台開發:從零基礎到ThinkPHP5高性能框架實踐 > 24.5.2 網頁授權防作弊 >

24.5.2 網頁授權防作弊

在抽獎類系統的開發中,防作弊是非常重要的安全措施之一。如果沒有防作弊機制,那麼可能所有獎品被作弊軟件一下就掃光了。

微信公眾平台提供的OAuth2.0網頁授權,可以限定用戶必須在微信中打開,並且可以通過查詢用戶的訂閱狀態限定已經關注微信公眾號的用戶才能參加活動。

下面是方倍工作室開發的微信公眾平台高級接口PHP SDK中關於OAuth2.0網頁授權的代碼。


require_once('configure.php');   // 引用配置
class class_weixin
{
    var $appid = APPID;
    var $appsecret = APPSECRET;

    // 構造函數,獲取Access Token
    public function __construct($appid = NULL, $appsecret = NULL)
    {
        if($appid && $appsecret){
            $this->appid = $appid;
            $this->appsecret = $appsecret;
        }
        $url = "https:// api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".
        $this->appid."&secret=".$this->appsecret;
        $res = $this->http_request($url);
        $result = json_decode($res, true);
        $this->access_token = $result["access_token"];
        $this->expires_time = time;
    }

    // 生成OAuth2.0的URL
    public function oauth2_authorize($redirect_url, $scope, $state = NULL)
    {
        $url = "https:// open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->
        appid."&redirect_uri=".$redirect_url."&response_type=code&scope=".$scope.
        "&state=".$state."#wechat_redirect";
        return $url;
}

    // 生成OAuth2.0的Access Token
    public function oauth2_access_token($code)
    {
        $url = "https:// api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid.
        "&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";
        $res = $this->http_request($url);
        return json_decode($res, true);
    }

    // HTTP請求(支持GET和POST)
    protected function http_request($url, $data = null)
    {
        $curl = curl_init;
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
  

上述代碼定義了構造函數及兩個成員函數,成員函數分別用於生成OAuth2.0的URL以及生成OAuth2.0的Access Token。


require_once('weixin.class.php');
$weixin = new class_weixin;
$openid = "";
if (!isset($_GET["code"])){
    $redirect_url = 'http:// '.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $jumpurl = $weixin->oauth2_authorize($redirect_url, "snsapi_base", "123");
    Header("Location: $jumpurl");
}else{
    $access_token = $weixin->oauth2_access_token($_GET["code"]);
    $openid = $access_token['openid'];
}
  

使用上述SDK時,先初始化一個類對象,通過判斷$_GET變量是否有code參數來決定當前是否要進行網頁授權,授權成功後再使用code值來換取access token,返回的access token信息中將包含openid,這樣就得到了用戶的OpenID。