Skip to content

Instantly share code, notes, and snippets.

@xfoxfu
Created February 25, 2014 12:21
Show Gist options
  • Select an option

  • Save xfoxfu/9207830 to your computer and use it in GitHub Desktop.

Select an option

Save xfoxfu/9207830 to your computer and use it in GitHub Desktop.
新浪微博用户名-密码获取token PHP
<?php
/**
* Get Token
*
* @return Access Token
* @throws Exception
*/
function SWAP( $username , $password , $app_key , $redirect_uri )
{
$username = urlencode( $username );
$password = urlencode( $password );
$app_key = urlencode( $app_key );
$redirect_uri = urlencode( $redirect_uri );
$ch = curl_init( 'https://api.weibo.com/oauth2/authorize' );
// post
$post_arr = array(
'client_id' => $app_key ,
'redirect_uri' => $redirect_uri ,
'action' => 'submit' ,
'response_type' => 'token' ,
'isLoginSina' => '0' ,
'from' => '' ,
'regCallback' => '' ,
'state' => '' ,
'ticket' => '' ,
'withOfficalFlag' => '0' ,
'userId' => $username ,
'passwd' => $password
);
$post = '';
foreach( $post_arr as $key => $value ){
$post = $post . '&' . $key . '=' . $value;
}
$post = substr( $post , 1 );
// header
$header = array(
'Referer: https://api.weibo.com/oauth2/authorize?client_id=' . $app_key . '&redirect_uri=' . $redirect_uri ,
'Content-Type: application/x-www-form-urlencoded'
);
curl_setopt( $ch , CURLOPT_POST , 1 );
curl_setopt( $ch , CURLOPT_POSTFIELDS , $post );
curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , FALSE );
curl_setopt( $ch , CURLOPT_SSL_VERIFYHOST , FALSE );
curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
curl_setopt( $ch , CURLOPT_HTTPHEADER , $header );
curl_setopt( $ch , CURLOPT_FOLLOWLOCATION , 0 );
curl_setopt( $ch , CURLOPT_HEADER , 2 );
// exec
$r = curl_exec( $ch );
if( curl_errno( $ch ) != 0 ){
throw new Exception( 'cURL error.' . curl_error( $ch ) , curl_errno( $ch ) );
}
if( curl_getinfo( $ch , CURLINFO_HTTP_CODE ) != 200 ){
$redirect_uri = urldecode( $redirect_uri );
$redirect_uri = str_replace( '/' , '\/' , $redirect_uri );
preg_match( '/Location: ' . $redirect_uri . '#access_token=.*&remind_in=/' , $r , $match );
$redirect_uri = str_replace( '\/' , '/' , $redirect_uri );
$rt = str_replace( 'Location: ' . $redirect_uri . '#access_token=' , '' , $match[ 0 ] );
$rt = str_replace( '&remind_in=' , '' , $rt );
return $rt;
} else{
throw new Exception( 'SINA api error:' . $r );
}
}
@xfoxfu
Copy link
Author

xfoxfu commented Feb 26, 2014

需要一下更新。。。http状态码验证今晚修改一下,从非200改为301或302

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment