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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles