名著阅读 > 微信公众平台开发:从零基础到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。