网站第三方登录(php版)

第三方登陆,顾名思义:用其他媒体的账号登陆一些网站,现在比较流行的第三方账号一般是:QQ,微博,微信。其他的平台也有,比如:人人,百度贴吧等,感觉这几个没有前面那三个出名,也没有前面那三个用的多,所以今天就说当前最为常用的微博和QQ的登陆方法。

微博登陆

  先说使用新浪微博账号登陆我的网站,微博登陆我理解是有两种:一种是通过前台JS调用不涉及后端的代码就可以实现登陆的功能,另一种是通过 SDK进行自己写页面和弹出确认框,自己处理逻辑,下面我会将这两种方法都写一下(其实也不算是两种,只是大体上称为前端和后端 - SDK不一样嘛):

第一种:

  1、先登陆微博的开放平台:http://open.weibo.com,在我的应用中添加自己的网站或者是应用,网站的话域名必须是备案过的 域名,不备案的域名禁止添加。我添加是 "答疑之家",等待审核,审通过添加成功之后,点击应用进去之后会看到左边的导航里面有个导航:部署微链接 ->微博登陆 ->微博登陆详细介绍里面就是微博登陆涉及到的文档的添加的步骤。

1464334293582988.png


2.放置登陆按钮,逻辑大致如下:

通过WBML方式

01
02
03
04
05
06
07
08
09
10
11
12
13
14
<!--没有回调函数的登录按钮-->                 
<wb:login-button type= "3,2"  ></wb:login-button>
  
<!--有回调函数的登录按钮-->      
<wb:login-button type= "3,2"  onlogin= "login"  onlogout= "logout"  ></wb:login-button>
 
// 如需添加回调函数,请在wbml标签中添加onlogin="login" onlogout="logout",并定义login和logout函数。
function  login(o) {
     alert(o.screen_name)
}
  
function  logout() {
     alert( 'logout' );
}

通过Js的方式:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
<div id= "wb_connect_btn"  ></div>
 
WB2.anyWhere( function  (W) {
     W.widget.connectButton({
         id:  "wb_connect_btn" ,
         type:  '3,2' ,
         callback: {
             login:  function  (o) {  //登录后的回调函数
                 alert( "login: "  + o.screen_name)
             },
             logout:  function  () {  //退出后的回调函数
                 alert( 'logout' );
             }
         }
     });
});

添加必要的Js文件:

在HTML标签中增加XML命名空间

1
<html xmlns:wb= "http://open.weibo.com/wb" >

在HEAD头中引入WB.JS

1
<script src= "http://tjs.sjs.sinajs.cn/open/api/js/wb.js?appkey=4121744546"  type= "text/javascript"  charset= "utf-8" ></script>

在需要部署登录按钮的位置粘贴WBML代码

<wb:login-button type="3,2" onlogin="login" onlogout="logout">登录按钮</wb:login-button>

第二种:通过PHP-SDK的方式

这种感觉符合我的需要,可以直接在PHP端处理登陆后的逻辑,前端可以写自己想要的授权打开方式,所以我改用的这一种,首先你需要看一下文 档:http://open.weibo.com/wiki/%E6%8E%88%E6%9D%83%E6%9C%BA%E5%88%B6

1:下载PHP-SDK开发包(http://open.weibo.com/wiki/SDK),借助于sdk能让你减少好多不必考虑的东西,所 以下载文档还是很有必要的,不过牛逼的你可以袭击写调用方式,毕竟那个文档写的也不咋滴,因为他的代码风格并不是按照PHP PSR(http://www.kancloud.cn/thinkphp/php-fig-psr/3140)规范去写的,感觉很不专业,毕竟是让别人 看的东西,规范是很重要的,至少不会挨那么多骂,哈哈!题外话啊!下面看看他的代码,你就该想吐槽了。。。。(换行方式,缩进,if 规范.. 不能忍)

值得注意的是你要记住自己的app id 与key,然后在sdk中换成自己的id

1464334458540862.png


2:前端open登陆授权页面,我是直接通过打开窗口的方式:

1
2
3
4
5
function  oauthLogin() {
      var  A = window.open(
          "http://***/public/tencentopen.html" "TencentLogin"
          "width=755, height=550,left=300px,top=60px,menubar=0,scrollbars=1,resizable=1,status=1,titlebar=0,toolbar=0,location=1" );
}

请求地址的处理逻辑:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
/**
      * 微博打开登陆认证页面
      * code:5000004
      * time:2016.4.28
      */
     public  function  weiboopen()
     {
         include_once ( 'weiboOauth/config.php'  );
         include_once ( 'weiboOauth/saetv2.ex.class.php' );
 
         $weiboObj  new  \SaeTOAuthV2(WB_AKEY, WB_SKEY );
         $code_url  $weiboObj ->getAuthorizeURL(WB_CALLBACK_URL);
 
         header( "Location:"  $code_url );
     }

3:用户点击微博登陆后的认证返回逻辑:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
      * 执行微博认证
      * code:5000005
      * time:2016.4.28
      */
     public  function  weibooauth()
     {
         include_once ( 'weiboOauth/config.php'  );
         include_once ( 'weiboOauth/saetv2.ex.class.php'  );
 
         $weiboObj  new  \SaeTOAuthV2(WB_AKEY, WB_SKEY);
 
         if  (isset( $_REQUEST [ 'code' ])) {
             $keys  array ();
             $keys [ 'code' ] =  $_REQUEST [ 'code' ];
             $keys [ 'redirect_uri' ] = WB_CALLBACK_URL;
             try  {
                 $token  $weiboObj ->getAccessToken( 'code' $keys ) ;
             catch  (OAuthException  $e ) {}
         }
 
         $succ [ 'code' ] =  '100' ;
         $succ [ 'message' ] =  '授权成功' ;
 
         $erro [ 'code' ] =  '101' ;
         $erro [ 'message' ] =  '授权失败' ;
 
         if ( empty ( $token )) {
             $msg  $erro ;
         else  {
             $saeObj  new  \SaeTClientV2(WB_AKEY, WB_SKEY,  $token [ 'access_token' ]);
             $user_info  $saeObj ->show_user_by_id( $token [ 'uid' ]);
             $ret  $this ->oauthLogin( $user_info 'weibo' );
 
             //授权失败
             if ( empty ( $ret )) {
                 $msg  $erro ;
             else  {
                 session( 'olas_access_token' $token [ 'access_token' ]);
                 $msg  $succ ;
             }
         }
 
         $this ->assign( 'msg' $msg );
         $this ->display( 'oauth' );
     }

4:授权成功以后:

  成功以后,你会把用户的信息写入到数据库,微博登陆会返回用户的昵称,头像信息(各个版本大小的头像),用户的性别等等,还有非常用户的用户 uid,这个非常重要的,下次登陆会检查这个UID是不是通过微博登陆过。这个和腾讯的不一样,腾讯的不反回UID而是一个openid,不过性质是一样 的,待会我会介绍。

之后返回打开窗口的状态码,刷新父页面进行跳转。

01
02
03
04
05
06
07
08
09
10
11
12
$(document).ready( function (){
       if ($.trim($( "#code" ).val()) ==  '100' ) {
              $( '#bodys' ).html( "<div>授权成功,正在跳转 . . .</div>" );
              setTimeout( "changewindows();" , 800);
       else  {
               $( '#bodys' ).html( "<div style='color:red;'>授权失败,请重试!</div>" );
       }
});
function  changewindows(){
       window.opener.location.href =  'http://**' ;
       window.close();
}

        可以了通过SDK中SaeTClientV2中的show_user_by_id就可以得到用户的信息了。你还可以看到那个Sae***因为这个 PHP版本是SAE部门维护的,所以只SAE开头的。步骤挺简单的,大家可以认证阅读他的开发文档,反复调试应该不成问题。我看SDK是对微博开发文档的 封装:OAuth2/authorize, OAuth2/access_tokenOAuth2/get_token_infoOAuth2/revokeoauth2OAuth2/get_oauth2_token

如果你在接入中有什么问题你可以直接联系我

QQ登陆

  使用QQ登陆也是很常见的,毕竟使用QQ的人多啊!使用QQ就必须按照人家的规范来,不然人家不给授权啊!下面是步骤:

1:和微博一样,首先要申请使用QQ互联,网址:http://connect.qq.com/manage/index 。首先创建应用,审核通过,不通过也可以使用,不过有限制,好像只能使用你自己的账号登陆,如下图:


1464334700267544.png

2:一旦通过审核以后你就可以添加和修改自己网站的一些登陆信息,点击 应用基本信息,这里要特别注意回调地址,因为一旦写错不能进行授权认证,所以回调地址要特别的注意,我在接入的时候就是一直报错。还有一个要注意的是添加 协作者,这个可以用作测试,很有用的。下面是我自己的网站添加的信息,大家可以瞅瞅,不过关键信息我已经抹去了,隐私嘛。

1464334758530071.jpg

3:上面的进行完之后,你就可以下载sdk了(http://wiki.connect.qq.com/sdk%E4%B8%8B%E8%BD %BD),我下的是PHP-sdk,下载后把他放在根目录就可以了。然后本地访问配置(主要是配置自己的应用信息),它上面有一个例子,直接可以调用的那 种

然后直接js打开授权页,页面地址请求到后台的方法:

01
02
03
04
05
06
07
08
09
10
11
/**
      * qq打开登陆认证页面
      * code:5000006
      * time:2016.4.24
      */
  public  function  tencentopen()
  {
      include_once ( "tencentOauth/qqConnectAPI.php" );
      $qc  new  \QC();
      $qc ->qq_login();
  }

授权成功以后要再次初始化那个sdk类:感觉这是他的BUG,必须拿上一次登陆返回的acs和open_id去初始化QC重新得到用户的信息。

1
2
3
4
5
6
7
8
//申请开发$openid
  $obj  new  \QC();
  $acs  $obj ->qq_callback();
  $openid  $obj ->get_openid();
 
  //重新赋值,得到用户信息
  $qc  new  \QC( $acs $openid );
  $user_info  $qc ->get_user_info();

完整的代码如下:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
      * qq登陆认证逻辑
      * code:5000007
      * time:2016.4.24
      */
     public  function  oauth()
     {
         include_once ( "tencentOauth/qqConnectAPI.php" );
 
         //申请开发$openid
         $obj  new  \QC();
         $acs  $obj ->qq_callback();
         $openid  $obj ->get_openid();
 
         //重新赋值,得到用户信息
         $qc  new  \QC( $acs $openid );
         $user_info  $qc ->get_user_info();
 
         $succ [ 'code' ] =  '100' ;
         $succ [ 'message' ] =  '授权成功' ;
 
         $erro [ 'code' ] =  '101' ;
         $erro [ 'message' ] =  '授权失败' ;
 
         $msg  = [];
         if ( empty ( $user_info )) {
             $msg  $erro ;
         else  {
             $user_info [ 'openid' ] =  $openid ;
             $user_info [ 'appid' ] = C( 'QQ_APPID' );
             $ret  $this ->oauthLogin( $user_info 'tencent' );
             
             //授权失败
             if ( empty ( $ret )) {
                 $msg  $erro ;
             else  {
                 $msg  $succ ;
             }
         }
 
         $this ->assign( 'msg' $msg );
         $this ->display( 'oauth' );
     }

        这里要注意QQ和微博返回用户的ID是不一样的,微博返回的就是用户在微博的真实id,但是QQ不是。他返回的是qq号对应的一个open_Id, 感觉腾讯有点扯淡,这直接导致,你无法得到登陆者的QQ号,有点悲哀,只得到一个和QQ号一一对应的open_id,也算不错了,哎!

        好了,到这里基本上把微博和QQ的登陆说完了,期间或遇到各种的问题,比如回调地址失败,登陆之后刷新父页面跳转等等,设计到各种的用户体验。

 文章出处:http://www.zhaoyafei.cn/content.html?id=45

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
THINKPHP最全第三方登录(包括腾讯QQ、微信、新浪微博、Github、淘宝网、百度、搜狐微博、人人、360、网易等等) 使用方式: 1、使用命名空间 use Org\ThinkSDK\ThinkOauth; 2、设置三方登录的类别并赋予一个变量 $type = ThinkOauth::getInstance('qq'); 3、设置配置文件 'THINK_SDK_(TYPE)' => array( 'APP_KEY' => '', //应用注册成功后分配的 APP ID 'APP_SECRET' => '', //应用注册成功后分配的KEY 'CALLBACK' => '', //注册应用填写的callback ), 上文中的(TYPE)为设置的类别,其值目前有以下几个: //腾讯QQ登录配置 THINK_SDK_QQ // 用户基本信息API接口 user/get_user_info //腾讯微博配置 THINK_SDK_TENCENT // 用户基本信息API接口 user/info //新浪微博配 THINK_SDK_SINA // 用户基本信息API接口 users/show。附加参数:'uid='.$obj->openid() //网易微博配置 THINK_SDK_T163 // 用户基本信息API接口 users/show //人人网配置 THINK_SDK_RENREN // 用户基本信息API接口 users.getInfo //360配置 THINK_SDK_X360 // 用户基本信息API接口 user/me //豆瓣配置 THINK_SDK_DOUBAN // 用户基本信息API接口 user/~me //Github配置 THINK_SDK_GITHUB // 用户基本信息API接口 user //Google配置 THINK_SDK_GOOGLE // 用户基本信息API接口 userinfo //MSN配置 THINK_SDK_MSN // 用户基本信息API接口 msn。附加参数:token //点点配置 THINK_SDK_DIANDIAN // 用户基本信息API接口 user/info //淘宝网配置 THINK_SDK_TAOBAO // 用户基本信息API接口 taobao.user.buyer.get。附加参数:'fields=user_id,nick,sex,buyer_credit,avatar,has_shop,vip_info' //百度配置 THINK_SDK_BAIDU // 用户基本信息API接口 passport/users/getLoggedInUser // 注意,百度的头像位置是http://tb.himg.baidu.com/sys/portrait/item/{$data['portrait']} //开心网配置 THINK_SDK_KAIXIN // 用户基本信息API接口 users/me //搜狐微博配置 THINK_SDK_SOHU // 用户基本信息API接口 i/prv/1/user/get-basic-info 4、实例化一个登录页面 redirect($type->getRequestCodeURL()); 这里的$type是第二部获取的结果 5、回调页面 $code = $this->get('code'); $type = 'QQ'; $sns = ThinkOauth::getInstance($type); //腾讯微博需传递的额外参数 $extend = null; if($type == 'tencent'){ $extend = array('openid' => $this->_get('openid'), 'openkey' => $this->_get('openkey')); } //请妥善保管这里获取到的Tok
[![Build Status](https://travis-ci.org/google/google-api-php-client.svg?branch=master)](https://travis-ci.org/google/google-api-php-client) # Google APIs Client Library for PHP # The Google API Client Library enables you to work with Google APIs such as Google+, Drive, or YouTube on your server. These client libraries are officially supported by Google. However, the libraries are considered complete and are in maintenance mode. This means that we will address critical bugs and security issues but will not add any new features. ## Google Cloud Platform For Google Cloud Platform APIs such as Datastore, Cloud Storage or Pub/Sub, we recommend using [GoogleCloudPlatform/google-cloud-php](https://github.com/GoogleCloudPlatform/google-cloud-php) which is under active development. ## Requirements ## * [PHP 5.4.0 or higher](http://www.php.net/) ## Developer Documentation ## http://developers.google.com/api-client-library/php ## Installation ## You can use **Composer** or simply **Download the Release** ### Composer The preferred method is via [composer](https://getcomposer.org). Follow the [installation instructions](https://getcomposer.org/doc/00-intro.md) if you do not already have composer installed. Once composer is installed, execute the following command in your project root to install this library: ```sh composer require google/apiclient:"^2.0" ``` Finally, be sure to include the autoloader: ```php require_once '/path/to/your-project/vendor/autoload.php'; ``` ### Download the Release If you abhor using composer, you can download the package in its entirety. The [Releases](https://github.com/google/google-api-php-client/releases) page lists all stable versions. Download any file with the name `google-api-php-client-[RELEASE_NAME].zip` for a package including this library and its dependencies. Uncompress the zip file you download, and include the autoloader in your project: ```php require_once '/path/to/google-api-php-client/vendor/autoload.php'; ``` For additional installation and setup instructions, see [the documentation](https://developers.google.com/api-client-library/php/start/installation). ## Examples ## See the [`examples/`](examples) directory for examples of the key client features. You can view them in your browser by running the php built-in web server. ``` $ php -S localhost:8000 -t examples/ ``` And then browsing to the host and port you specified (in the above example, `http://localhost:8000`). ### Basic Example ### ```php // include your composer dependencies require_once 'vendor/autoload.php'; $client = new Google_Client(); $client->setApplicationName("Client_Library_Examples"); $client->setDeveloperKey("YOUR_APP_KEY"); $service = new Google_Service_Books($client); $optParams = array('filter' => 'free-ebooks'); $results = $service->volumes->listVolumes('Henry David Thoreau', $optParams); foreach ($results as $item) { echo $item['volumeInfo']['title'], "<br /> \n"; } ``` ### Authentication with OAuth ### > An example of this can be seen in [`examples/simple-file-upload.php`](examples/simple-file-upload.php). 1. Follow the instructions to [Create Web Application Credentials](https://developers.google.com/api-client-library/php/auth/web-app#creatingcred) 1. Download the JSON credentials 1. Set the path to these credentials using `Google_Client::setAuthConfig`: ```php $client = new Google_Client(); $client->setAuthConfig('/path/to/client_credentials.json'); ``` 1. Set the scopes required for the API you are going to call ```php $client->addScope(Google_Service_Drive::DRIVE); ``` 1. Set your application's redirect URI ```php // Your redirect URI can be any registered URI, but in this example // we redirect back to this same page $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; $client->setRedirectUri($redirect_uri); ``` 1. In the script handling the redirect URI, exchange the authorization code for an access token: ```php if (isset($_GET['code'])) { $token = $client->fetchAccessTokenWithAuthCode($_GET['code']); } ``` ### Authentication with Service Accounts ### > An example of this can be seen in [`examples/service-account.php`](examples/service-account.php). Some APIs (such as the [YouTube Data API](https://developers.google.com/youtube/v3/)) do not support service accounts. Check with the specific API documentation if API calls return unexpected 401 or 403 errors. 1. Follow the instructions to [Create a Service Account](https://developers.google.com/api-client-library/php/auth/service-accounts#creatinganaccount) 1. Download the JSON credentials 1. Set the path to these credentials using the `GOOGLE_APPLICATION_CREDENTIALS` environment variable: ```php putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json'); ``` 1. Tell the Google client to use your service account credentials to authenticate: ```php $client = new Google_Client(); $client->useApplicationDefaultCredentials(); ``` 1. Set the scopes required for the API you are going to call ```php $client->addScope(Google_Service_Drive::DRIVE); ``` 1. If you have delegated domain-wide access to the service account and you want to impersonate a user account, specify the email address of the user account using the method setSubject: ```php $client->setSubject($user_to_impersonate); ``` ### Making Requests ### The classes used to call the API in [google-api-php-client-services](https://github.com/Google/google-api-php-client-services) are autogenerated. They map directly to the JSON requests and responses found in the [APIs Explorer](https://developers.google.com/apis-explorer/#p/). A JSON request to the [Datastore API](https://developers.google.com/apis-explorer/#p/datastore/v1beta3/datastore.projects.runQuery) would look like this: ```json POST https://datastore.googleapis.com/v1beta3/projects/YOUR_PROJECT_ID:runQuery?key=YOUR_API_KEY { "query": { "kind": [{ "name": "Book" }], "order": [{ "property": { "name": "title" }, "direction": "descending" }], "limit": 10 } } ``` Using this library, the same call would look something like this: ```php // create the datastore service class $datastore = new Google_Service_Datastore($client); // build the query - this maps directly to the JSON $query = new Google_Service_Datastore_Query([ 'kind' => [ [ 'name' => 'Book', ], ], 'order' => [ 'property' => [ 'name' => 'title', ], 'direction' => 'descending', ], 'limit' => 10, ]); // build the request and response $request = new Google_Service_Datastore_RunQueryRequest(['query' => $query]); $response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request); ``` However, as each property of the JSON API has a corresponding generated class, the above code could also be written like this: ```php // create the datastore service class $datastore = new Google_Service_Datastore($client); // build the query $request = new Google_Service_Datastore_RunQueryRequest(); $query = new Google_Service_Datastore_Query(); // - set the order $order = new Google_Service_Datastore_PropertyOrder(); $order->setDirection('descending'); $property = new Google_Service_Datastore_PropertyReference(); $property->setName('title'); $order->setProperty($property); $query->setOrder([$order]); // - set the kinds $kind = new Google_Service_Datastore_Kind[removed]); $kind->setName('Book'); $query->setKinds([$kind]); // - set the limit $query->setLimit(10); // add the query to the request and make the request $request->setQuery($query); $response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request); ``` The method used is a matter of preference, but *it will be very difficult to use this library without first understanding the JSON syntax for the API*, so it is recommended to look at the [APIs Explorer](https://developers.google.com/apis-explorer/#p/) before using any of the services here. ### Making HTTP Requests Directly ### If Google Authentication is desired for external applications, or a Google API is not available yet in this library, HTTP requests can be made directly. The `authorize` method returns an authorized [Guzzle Client](http://docs.guzzlephp.org/), so any request made using the client will contain the corresponding authorization. ```php // create the Google client $client = new Google_Client(); /** * Set your method for authentication. Depending on the API, This could be * directly with an access token, API key, or (recommended) using * Application Default Credentials. */ $client->useApplicationDefaultCredentials(); $client->addScope(Google_Service_Plus::PLUS_ME); // returns a Guzzle HTTP Client $httpClient = $client->authorize(); // make an HTTP request $response = $httpClient->get('https://www.googleapis.com/plus/v1/people/me'); ``` ### Caching ### It is recommended to use another caching library to improve performance. This can be done by passing a [PSR-6](http://www.php-fig.org/psr/psr-6/) compatible library to the client: ```php use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; use Cache\Adapter\Filesystem\FilesystemCachePool; $filesystemAdapter = new Local(__DIR__.'/'); $filesystem = new Filesystem($filesystemAdapter); $cache = new FilesystemCachePool($filesystem); $client->setCache($cache); ``` In this example we use [PHP Cache](http://www.php-cache.com/). Add this to your project with composer: ``` composer require cache/filesystem-adapter ``` ### Updating Tokens ### When using [Refresh Tokens](https://developers.google.com/identity/protocols/OAuth2InstalledApp#refresh) or [Service Account Credentials](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#overview), it may be useful to perform some action when a new access token is granted. To do this, pass a callable to the `setTokenCallback` method on the client: ```php $logger = new Monolog\Logger; $tokenCallback = function ($cacheKey, $accessToken) use ($logger) { $logger->debug(sprintf('new access token received at cache key %s', $cacheKey)); }; $client->setTokenCallback($tokenCallback); ``` ### Debugging Your HTTP Request using Charles ### It is often very useful to debug your API calls by viewing the raw HTTP request. This library supports the use of [Charles Web Proxy](https://www.charlesproxy.com/documentation/getting-started/). Download and run Charles, and then capture all HTTP traffic through Charles with the following code: ```php // FOR DEBUGGING ONLY $httpClient = new GuzzleHttp\Client([ 'proxy' => 'localhost:8888', // by default, Charles runs on localhost port 8888 'verify' => false, // otherwise HTTPS requests will fail. ]); $client = new Google_Client(); $client->setHttpClient($httpClient); ``` Now all calls made by this library will appear in the Charles UI. One additional step is required in Charles to view SSL requests. Go to **Charles > Proxy > SSL Proxying Settings** and add the domain you'd like captured. In the case of the Google APIs, this is usually `*.googleapis.com`. ### Service Specific Examples ### YouTube: https://github.com/youtube/api-samples/tree/master/php ## How Do I Contribute? ## Please see the [contributing](CONTRIBUTING.md) page for more information. In particular, we love pull requests - but please make sure to sign the [contributor license agreement](https://developers.google.com/api-client-library/php/contribute). ## Frequently Asked Questions ## ### What do I do if something isn't working? ### For support with the library the best place to ask is via the google-api-php-client tag on StackOverflow: http://stackoverflow.com/questions/tagged/google-api-php-client If there is a specific bug with the library, please [file a issue](https://github.com/google/google-api-php-client/issues) in the Github issues tracker, including an example of the failing code and any specific errors retrieved. Feature requests can also be filed, as long as they are core library requests, and not-API specific: for those, refer to the documentation for the individual APIs for the best place to file requests. Please try to provide a clear statement of the problem that the feature would address. ### I want an example of X! ### If X is a feature of the library, file away! If X is an example of using a specific service, the best place to go is to the teams for those specific APIs - our preference is to link to their examples rather than add them to the library, as they can then pin to specific versions of the library. If you have any examples for other APIs, let us know and we will happily add a link to the README above! ### Why do you still support 5.2? ### When we started working on the 1.0.0 branch we knew there were several fundamental issues to fix with the 0.6 releases of the library. At that time we looked at the usage of the library, and other related projects, and determined that there was still a large and active base of PHP 5.2 installs. You can see this in statistics such as the PHP versions chart in the WordPress stats: http://wordpress.org/about/stats/. We will keep looking at the types of usage we see, and try to take advantage of newer PHP features where possible. ### Why does Google_..._Service have weird names? ### The _Service classes are generally automatically generated from the API discovery documents: https://developers.google.com/discovery/. Sometimes new features are added to APIs with unusual names, which can cause some unexpected or non-standard style naming in the PHP classes. ### How do I deal with non-JSON response types? ### Some services return XML or similar by default, rather than JSON, which is what the library supports. You can request a JSON response by adding an 'alt' argument to optional params that is normally the last argument to a method call: ``` $opt_params = array( 'alt' => "json" ); ``` ### How do I set a field to null? ### The library strips out nulls from the objects sent to the Google APIs as its the default value of all of the uninitialized properties. To work around this, set the field you want to null to `Google_Model::NULL_VALUE`. This is a placeholder that will be replaced with a true null when sent over the wire. ## Code Quality ## Run the PHPUnit tests with PHPUnit. You can configure an API key and token in BaseTest.php to run all calls, but this will require some setup on the Google Developer Console. phpunit tests/ ### Coding Style To check for coding style violations, run ``` vendor/bin/phpcs src --standard=style/ruleset.xml -np ``` To automatically fix (fixable) coding style violations, run ``` vendor/bin/phpcbf src --standard=style/ruleset.xml ```
谷歌第三方登录是一种利用谷歌账号登录第三方网站或应用程序的方式。在 PHP 中,我们可以使用谷歌提供的 OAuth 2.0 协议来实现这一功能。 首先,我们需要在谷歌开发者控制台上创建一个项目,并获取到谷歌提供的客户端ID和客户端密钥。接下来,我们需要安装并引入谷歌 PHP 客户端库。 在网站或应用程序中,我们可以提供一个链接或按钮,让用户点击以登录谷歌账号。当用户点击该链接时,我们将向谷歌发送一个授权请求,并重定向用户到谷歌登录页面。用户需要登录并授权我们的应用程序的访问权限。 一旦用户授权成功,谷歌将会将一个授权码发送回我们的重定向URL。我们可以通过在该URL中检索授权码来获取用户的访问令牌。然后,我们可以使用访问令牌来获取用户的谷歌账号信息。 在 PHP 中,我们可以使用谷歌客户端库提供的方法来完成上述步骤。首先,我们需要创建一个谷歌客户端对象,并设置我们在开发者控制台中获取到的客户端ID和客户端密钥。 然后,我们可以生成一个谷歌授权链接,并将用户重定向到该链接。当用户成功登录并授权后,我们可以使用谷歌客户端的 `fetchAccessTokenWithAuthCode` 方法来获取用户的访问令牌。 一旦我们获取到访问令牌,我们可以使用谷歌客户端的 `get` 方法来获取用户的谷歌账号信息,例如用户的姓名、电子邮件等。 最后,我们可以根据用户的谷歌账号信息进行相应的处理,例如创建新用户账号,或将其与现有用户账号进行关联。 通过这样的方式,我们就可以在 PHP 中实现谷歌第三方登录

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值