Home Backend Development PHP Tutorial PHP code to implement Sina, Tencent and Taobao login

PHP code to implement Sina, Tencent and Taobao login

Jul 25, 2016 am 08:56 AM

  1. session_start();

  2. class openlogin{
  3. public $_URL = "";
  4. public $config = array();

  5. public function __construct(){

  6. $this->openlogin();
  7. }
  8. function openlogin(){

  9. }

  10. /*获取登陆页面URL*/

  11. public function login_url(){
  12. if(empty($this->config)){
  13. return false;
  14. }
  15. $config = $this->config;
  16. $login_url = $config['login_url'];
  17. $_SESSION['state'] = $state = md5(uniqid(rand(), TRUE));
  18. $array = array(
  19. "response_type"=>"code",
  20. "state" => $state,
  21. "client_id"=>$config['appkey'],
  22. "redirect_uri"=>urlencode( $config['redirect_uri'] )
  23. );

  24. $this->set($array);

  25. $url = $this->combineURL($login_url , $this->_param);
  26. if($url){
  27. @header("Location:".$url);
  28. }else{
  29. return false;
  30. }
  31. }

  32. /*获取access_token*/

  33. public function get_access_token(){
  34. if(empty($this->config)){
  35. return false;
  36. }

  37. $config = $this->config;

  38. if(! $config['code'] = $_REQUEST['code'] ){

  39. return false;
  40. }

  41. $url = $config['authorization_url'];

  42. $state = $_SESSION['state'];
  43. $array = array(
  44. "grant_type"=>"authorization_code",
  45. "client_id" => $config['appkey'],
  46. "client_secret"=>$config['appsecret'],
  47. "code"=>$config['code'],
  48. "redirect_uri"=>urlencode( $config['redirect_uri'] ),
  49. "state"=>$state
  50. );
  51. $this->set($array);
  52. return $this->post_contents($url);
  53. }
  54. /* set $this->_param 数组*/
  55. public function set($array) {
  56. if(empty($array)){
  57. return false;
  58. }
  59. $this->_param = array();
  60. foreach($array as $name=>$value){
  61. $this->_param[$name] = $value;
  62. }
  63. }
  64. /**
  65. * post_contents
  66. * The server obtains the content through post request
  67. * @param string $url The requested url, spliced ​​
  68. * @return string The content returned by the request
  69. */
  70. public function post_contents($url){
  71. if(empty($url)){
  72. return false;
  73. }
  74. $param = $this->combineURL("" , $this->_param);
  75. $ch = curl_init();
  76. // 设置URL和相应的选项
  77. curl_setopt($ch, CURLOPT_URL, $url);
  78. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  79. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  80. curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
  81. curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
  82. curl_setopt($ch, CURLOPT_POST, 1);
  83. curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
  84. // 抓取URL并把它传递给浏览器
  85. $reponse = curl_exec($ch);
  86. curl_close($ch);
  87. return $reponse;
  88. }
  89. /**
  90. * get_contents
  91. * The server obtains the content through a get request
  92. * @param string $url The requested url, spliced ​​
  93. * @return string The content returned by the request
  94. */
  95. public function get_contents($url){
  96. $ch = curl_init();
  97. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  98. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  99. curl_setopt($ch, CURLOPT_URL, $url);
  100. $response = curl_exec($ch);
  101. curl_close($ch);

  102. //-------请求为空

  103. if(empty($response)){
  104. return false;
  105. }

  106. return $response;

  107. }

  108. /**

  109. * combineURL
  110. * splice url
  111. * @param string $baseURL based on url
  112. * @param array $keysArr parameter list array
  113. * @return string return the spliced ​​url
  114. */
  115. public function combineURL($baseURL,$keysArr){
  116. if( $baseURL=="" ){
  117. $combined = "";
  118. }else{
  119. $combined = $baseURL."?";
  120. }
  121. $valueArr = array();

  122. foreach($keysArr as $key => $val){

  123. $valueArr[] = "$key=$val";
  124. }

  125. $keyStr = implode("&",$valueArr);

  126. $combined .= ($keyStr);
  127. return $combined;
  128. }
  129. }

  130. //php实现QQ登录

  131. class qq_openlogin extends openlogin{
  132. private $openname = "qq";
  133. public $config = array(
  134. "appkey"=>"your appkey",
  135. "appsecret"=>"your appsecret",
  136. "redirect_uri"=>"XXXXX",
  137. "login_url" => "https://graph.qq.com/oauth2.0/authorize",
  138. "scope"=>"get_user_info,add_share,list_album,add_album,upload_pic,add_topic,add_one_blog,add_weibo,check_page_fans,add_t,add_pic_t,del_t,get_repost_list,
  139. get_info,get_other_info,get_fanslist,get_idolist,add_idol,del_idol,get_tenpay_addr",
  140. "authorization_url"=>"https://graph.qq.com/oauth2.0/token"
  141. );

  142. function __construct()

  143. {
  144. $this->qq_openlogin();
  145. }
  146. function qq_openlogin(){
  147. parent::__construct();
  148. }

  149. function get_access_token(){

  150. $response = parent::get_access_token();
  151. /*检测错误是否发生*/
  152. if(strpos($response, "callback") !== false){

  153. $lpos = strpos($response, "(");

  154. $rpos = strrpos($response, ")");
  155. $response = substr($response, $lpos + 1, $rpos - $lpos -1);
  156. $msg = json_decode($response);

  157. if(isset($msg->error)){

  158. return false;
  159. }
  160. }

  161. $params = array();

  162. parse_str($response, $params);
  163. /*access_token == $params[access_token]*/
  164. /*获取 openid */
  165. $response = $this->get_contents("https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token']);

  166. //--------检测错误是否发生

  167. if(strpos($response, "callback") !== false){

  168. $lpos = strpos($response, "(");

  169. $rpos = strrpos($response, ")");
  170. $response = substr($response, $lpos + 1, $rpos - $lpos -1);
  171. }

  172. $user = json_decode($response);

  173. if(isset($user->error)){
  174. return false;
  175. }

  176. /*

  177. Parameters required to obtain user information: openid (user’s ID, one-to-one correspondence with QQ number), access_token (Access_Token can be obtained by using Authorization_Code or access_token has a validity period of 3 months ),oauth_consumer_key(user appid),format(return format)
  178. */
  179. /*Database save*/
  180. $open_param = array(
  181. "openid"=>$user->openid,
  182. "access_token"=> ;$params['access_token']
  183. );
  184. //
  185. $open_param['oauth_consumer_key'] = $this->config['appkey'];
  186. $open_param['format'] = "json";
  187. / *Splice url*/
  188. $get_user_url = $this->combineURL("https://graph.qq.com/user/get_user_info",$open_param);
  189. //Get user information
  190. $userinfo = $this-> ;get_contents($get_user_url);

  191. $userinfo = json_decode($userinfo);

  192. return $userinfo;

  193. }
  194. }

  195. //php implements Weibo login

  196. class weibo_openlogin extends openlogin{
  197. private $openname = "weibo";
  198. public $config = array(
  199. "appkey"=>"your appkey",
  200. "appsecret"= >"your appsecret",
  201. "login_url" => "https://api.weibo.com/oauth2/authorize",
  202. "redirect_uri"=>"XXXXXXX",
  203. "authorization_url"=>"https ://api.weibo.com/oauth2/access_token"
  204. );

  205. function __construct()

  206. {
  207. $this->qq_openlogin();
  208. }
  209. function qq_openlogin() {
  210. parent::__construct();
  211. }

  212. function get_access_token(){

  213. $response = parent::get_access_token();
  214. $userinfo = json_decode($response);
  215. return $ userinfo;
  216. }
  217. }

  218. //php implements Taobao login

  219. class taobao_openlogin extends openlogin{
  220. private $openname = "taobao";
  221. public $config = array(
  222. "appkey"=> ;"your appkey",
  223. "appsecret"=>"your appsecret",
  224. "redirect_uri"=>"XXXXX",
  225. "authorization_url"=>"https://oauth.taobao.com/token",
  226. "login_url"=>"https://oauth.taobao.com/authorize"
  227. );

  228. function __construct()

  229. {
  230. $this->qq_openlogin();
  231. }
  232. function qq_openlogin(){
  233. parent::__construct();
  234. }

  235. function get_access_token(){

  236. $response = parent::get_access_token();
  237. $userinfo = json_decode( $response);
  238. return $userinfo;
  239. }

  240. }

  241. if($_GET['openname']){
  242. $openname = $_GET['openname']."_openlogin";
  243. $openlogin = new $openname();
  244. if(!isset($_REQUEST['code'])){
  245. //Request url
  246. $url = $openlogin->login_url();
  247. if(!$url ){
  248. echo "0";
  249. exit();
  250. }
  251. }else{
  252. if(isset($_REQUEST["state"]) && ($_SESSION['state'] != $_REQUEST["state"] )){
  253. echo "1";
  254. exit();
  255. }
  256. $rs = $openlogin->get_access_token();
  257. print_r( $rs );
  258. }
  259. }
  260. ?>

Copy code

附,人人网登陆代码。

  1. class renren_openlogin extends openlogin{

  2. private $openname = "renren";
  3. public $config = array(
  4. "appid"=>"your appid",
  5. "appkey"=>"your appkey",
  6. "appsecret"=>"your secret key",
  7. "redirect_uri"=>"XXXXXX",
  8. "authorization_url"=>"https://graph.renren.com/oauth/token",
  9. "login_url"=>"https://graph.renren.com/oauth/authorize"
  10. );

  11. function __construct()

  12. {
  13. $this->qq_openlogin();
  14. }
  15. function qq_openlogin(){
  16. parent::__construct();
  17. }

  18. function get_access_token(){

  19. $response = parent::get_access_token();

  20. $userinfo = json_decode($response);

  21. return $userinfo;

  22. /*
  23. access_token:获取的Access Token;
  24. expires_in:Access Token的有效期,以秒为单位;
  25. refresh_token:用于刷新Access Token 的 Refresh Token,长期有效,不会过期;
  26. scope:Access Token最终的访问范围,既用户实际授予的权限列表(用户在授权页面时,有可能会取消掉某些请求的权限)。关于权限的具体信息请参考
  27. */
  28. }

  29. /*获取登陆页面URL*/

  30. public function login_url(){
  31. if(empty($this->config)){
  32. return false;
  33. }
  34. $config = $this->config;
  35. $login_url = $config['login_url'];
  36. $array = array(
  37. "response_type"=>"code",
  38. "client_id"=>$config['appid'],
  39. "redirect_uri"=>urlencode( $config['redirect_uri'] )
  40. );

  41. $this->set($array);

  42. $url = $this->combineURL($login_url , $this->_param);

  43. if($url){

  44. @header("Location:".$url);
  45. }else{
  46. return false;
  47. }
  48. }
  49. }

复制代码


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles