찾다
php教程PHP源码新浪微博的账号登录及api操作

新浪微博的账号登录及api操作,使用oauth 2.0 
官方提供的sdk都太过庞大,这是我自己简化的,提供简单的账号登录、获取个人信息、发布分享等功能,如果需要其他功能可以根据官方的api文档自行添加

更新:修改index.php中的bug;如果要使用session,请在index.php和callback.php中添加“session_start();”

sina.php

<?php
/**
 * PHP Library for weibo.com
 *
 * @author PiscDong (http://www.piscdong.com/)
 */
class sinaPHP
{
    function __construct($client_id, $client_secret, $access_token=NULL){
        $this->client_id=$client_id;
        $this->client_secret=$client_secret;
        $this->access_token=$access_token;
    }
 
    function login_url($callback_url){
        $params=array(
            &#39;response_type&#39;=>&#39;code&#39;,
            &#39;client_id&#39;=>$this->client_id,
            &#39;redirect_uri&#39;=>$callback_url
        );
        return &#39;https://api.weibo.com/oauth2/authorize?&#39;.http_build_query($params);
    }
 
    function access_token($callback_url, $code){
        $params=array(
            &#39;grant_type&#39;=>&#39;authorization_code&#39;,
            &#39;code&#39;=>$code,
            &#39;client_id&#39;=>$this->client_id,
            &#39;client_secret&#39;=>$this->client_secret,
            &#39;redirect_uri&#39;=>$callback_url
        );
        $url=&#39;https://api.weibo.com/oauth2/access_token&#39;;
        return $this->http($url, http_build_query($params), &#39;POST&#39;);
    }
 
    /**
    function access_token_refresh($refresh_token){
    }
    **/
 
    function get_uid(){
        $params=array();
        $url=&#39;https://api.weibo.com/2/account/get_uid.json&#39;;
        return $this->api($url, $params);
    }
 
    function show_user_by_id($uid){
        $params=array(
            &#39;uid&#39;=>$uid
        );
        $url=&#39;https://api.weibo.com/2/users/show.json&#39;;
        return $this->api($url, $params);
    }
 
    function statuses_count($ids){
        $params=array(
            &#39;ids&#39;=>$ids
        );
        $url=&#39;https://api.weibo.com/2/statuses/count.json&#39;;
        return $this->api($url, $params);
    }
 
    function get_comments_by_sid($id, $count=10, $page=1){
        $params=array(
            &#39;id&#39;=>$id,
            &#39;page&#39;=>$page,
            &#39;count&#39;=>$count
        );
        $url=&#39;https://api.weibo.com/2/comments/show.json&#39;;
        return $this->api($url, $params);
    }
 
    function repost_timeline($id, $count=10, $page=1){
        $params=array(
            &#39;id&#39;=>$id,
            &#39;page&#39;=>$page,
            &#39;count&#39;=>$count
        );
        $url=&#39;https://api.weibo.com/2/statuses/repost_timeline.json&#39;;
        return $this->api($url, $params);
    }
 
    function update($img_c, $pic=&#39;&#39;){
        $params=array(
            &#39;status&#39;=>$img_c
        );
        if($pic!=&#39;&#39; && is_array($pic)){
            $url=&#39;https://api.weibo.com/2/statuses/upload.json&#39;;
            $params[&#39;pic&#39;]=$pic;
        }else{
            $url=&#39;https://api.weibo.com/2/statuses/update.json&#39;;
        }
        return $this->api($url, $params, &#39;POST&#39;);
    }
 
    function user_timeline($uid, $count=10, $page=1){
        $params=array(
            &#39;uid&#39;=>$uid,
            &#39;page&#39;=>$page,
            &#39;count&#39;=>$count
        );
        $url=&#39;https://api.weibo.com/2/statuses/user_timeline.json&#39;;
        return $this->api($url, $params);
    }
 
    function querymid($id, $type=1, $is_batch=0){
        $params=array(
            &#39;id&#39;=>$id,
            &#39;type&#39;=>$type,
            &#39;is_batch&#39;=>$is_batch
        );
        $url=&#39;https://api.weibo.com/2/statuses/querymid.json&#39;;
        return $this->api($url, $params);
    }
 
    function api($url, $params, $method=&#39;GET&#39;){
        $params[&#39;access_token&#39;]=$this->access_token;
        if($method==&#39;GET&#39;){
            $result=$this->http($url.&#39;?&#39;.http_build_query($params));
        }else{
            if(isset($params[&#39;pic&#39;])){
                uksort($params, &#39;strcmp&#39;);
                $str_b=uniqid(&#39;------------------&#39;);
                $str_m=&#39;--&#39;.$str_b;
                $str_e=$str_m. &#39;--&#39;;
                $body=&#39;&#39;;
                foreach($params as $k=>$v){
                    if($k==&#39;pic&#39;){
                        if(is_array($v)){
                            $img_c=$v[2];
                            $img_n=$v[1];
                        }elseif($v{0}==&#39;@&#39;){
                            $url=ltrim($v, &#39;@&#39;);
                            $img_c=file_get_contents($url);
                            $url_a=explode(&#39;?&#39;, basename($url));
                            $img_n=$url_a[0];
                        }
                        $body.=$str_m."\r\n";
                        $body.=&#39;Content-Disposition: form-data; name="&#39;.$k.&#39;"; filename="&#39;.$img_n.&#39;"&#39;."\r\n";
                        $body.="Content-Type: image/unknown\r\n\r\n";
                        $body.=$img_c."\r\n";
                    }else{
                        $body.=$str_m."\r\n";
                        $body.=&#39;Content-Disposition: form-data; name="&#39;.$k."\"\r\n\r\n";
                        $body.=$v."\r\n";
                    }
                }
                $body.=$str_e;
                $headers[]="Content-Type: multipart/form-data; boundary=".$str_b;
                $result=$this->http($url, $body, &#39;POST&#39;, $headers);
            }else{
                $result=$this->http($url, http_build_query($params), &#39;POST&#39;);
            }
        }
        return $result;
    }
 
    function http($url, $postfields=&#39;&#39;, $method=&#39;GET&#39;, $headers=array()){
        $ci=curl_init();
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        if($method==&#39;POST&#39;){
            curl_setopt($ci, CURLOPT_POST, TRUE);
            if($postfields!=&#39;&#39;)curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
        }
        $headers[]="User-Agent: sinaPHP(piscdong.com)";
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLOPT_URL, $url);
        $response=curl_exec($ci);
        curl_close($ci);
        $json_r=array();
        if($response!=&#39;&#39;)$json_r=json_decode($response, true);
        return $json_r;
    }
}

config.php

<?php
//配置文件
header(&#39;Content-Type: text/html; charset=UTF-8&#39;);
 
$sina_k=&#39;&#39;; //新浪微博应用App Key
$sina_s=&#39;&#39;; //新浪微博应用App Secret
$callback_url=&#39;http://yoururl/callback.php&#39;; //授权回调网址
?>

index.php

<?php
session_start(); //此示例中要使用session
require_once(&#39;config.php&#39;);
require_once(&#39;sina.php&#39;);
 
function getimgp($u){
    //图片处理
    $c=@file_get_contents($u);
    $name=md5($u).&#39;.jpg&#39;;
    $mime=&#39;image/unknown&#39;;
    return array($mime, $name, $c);
}
 
$sina_t=isset($_SESSION[&#39;sina_t&#39;])?$_SESSION[&#39;sina_t&#39;]:&#39;&#39;;
 
//检查是否已登录
if($sina_t!=&#39;&#39;){
    $sina=new sinaPHP($sina_k, $sina_s, $sina_t);
 
    //获取登录用户id
    $sina_uid=$sina->get_uid();
    $uid=$sina_uid[&#39;uid&#39;];
 
    //获取登录用户信息
    $result=$sina->show_user_by_id($uid);
    var_dump($result);
 
    /**
    //发布微博
    $content=&#39;微博内容&#39;;
    $img=&#39;http://www.baidu.com/img/baidu_sylogo1.gif&#39;;
    $img_a=getimgp($img);
    if($img_a[2]!=&#39;&#39;){
        $result=$sina->update($content, $img_a);
        //发布带图片微博
    }else{
        $result=$sina->update($content);
        //发布纯文字微博
    }
    var_dump($result);
    **/
 
    /**
    //微博列表
    $result=$sina->user_timeline($uid);
    var_dump($result);
    **/
 
}else{
    //生成登录链接
    $sina=new sinaPHP($sina_k, $sina_s);
    $login_url=$sina->login_url($callback_url);
    echo &#39;<a href="&#39;,$login_url,&#39;">点击进入授权页面</a>&#39;;
}
?>

4.callback.php

<?php
//授权回调页面,即配置文件中的$callback_url
session_start(); //此示例中要使用session
require_once(&#39;config.php&#39;);
require_once(&#39;sina.php&#39;);
 
if(isset($_GET[&#39;code&#39;]) && $_GET[&#39;code&#39;]!=&#39;&#39;){
    $o=new sinaPHP($sina_k, $sina_s);
    $result=$o->access_token($callback_url, $_GET[&#39;code&#39;]);
}
if(isset($result[&#39;access_token&#39;]) && $result[&#39;access_token&#39;]!=&#39;&#39;){
    echo &#39;授权完成,请记录<br/>access token:<input size="50" value="&#39;,$result[&#39;access_token&#39;],&#39;">&#39;;
 
    //保存登录信息,此示例中使用session保存
    $_SESSION[&#39;sina_t&#39;]=$result[&#39;access_token&#39;]; //access token
}else{
    echo &#39;授权失败&#39;;
}
echo &#39;<br/><a href="./">返回</a>&#39;;
?>
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기