获取微信公众号openid

//获取用户基本信息

public function getUser()

{

        $appid='';

        $secret='';

        $redirect_uri='';

        if (input('code')) {

                $code = input('code');

                $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";

                $result=$this->request($url);

                if (!$result) {

                        return false;

                }

            $arr=json_decode($result,true);

            var_dump($arr);

       }else{

    $url="https://open.weixin.qq.com/connect/oauth2/authorize?    appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";

        header("Location: ".$url);

        exit();

    }

}

private function request($url,$data=null){

        $curl=curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);

        //设定为不验证证书和host

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if(!empty($data)){

            curl_setopt($curl, CURLOPT_POST, true);

            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        }

        // 将curl_exec()获取的信息以文件流的形式返回,而不是直接输出

        curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);

        $output=curl_exec($curl);

        if (false===$output) {

                echo "
",curl_error($curl),"
";

                return false;

        }

        curl_close($curl);

           return $output;

}

你可能感兴趣的:(获取微信公众号openid)