csna_qq.module 2.54 KB
<?php

/**
 * @file
 * The CSNA QQ module is a sub-module of the Chinese Social Networks
 * Authentication (CSNA) framework allowing integration with the QQ OAuth
 * protocol for Authentication/Login.
 */

/**
 * Implements hook_csna_provider_info().
 */
function csna_qq_csna_provider_info() {
  $providers = array();

  $providers['qq'] = array(
    'title' => t('QQ'),
    'description' => t('Set your <strong>QQ authorized KEY</strong> and <strong>SECRET</strong> below.<br/>If you want to use an API key, you can get one at the !keylink.', array('!keylink' => l(t('QQ API website'), 'http://connect.qq.com/', array('attributes' => array('target' => '_blank'))))),
    'display_title' => csna_get_qq_button_image(),
    'type' => CSNA_OAUTH2,
    'authorize_uri' => 'https://graph.qq.com/oauth2.0/authorize',
    'access_token_uri' => 'https://graph.qq.com/oauth2.0/token',
    'info_uri' => 'https://graph.qq.com/user/get_user_info',
  );

  return $providers;
}

/**
 * Helper function for returning a themed image for the QQ display title.
 */
function csna_get_qq_button_image() {
  $image_arr = array(
    'path' => drupal_get_path('module', 'csna_qq') . '/qq_120x24.png',
    'title' => t('Sign in with QQ'),
    'alt' => t('Sign in with QQ'),
  );
  return theme('image', $image_arr);
}

/**
 * Implements hook_csna_provider_callback().
 */
function csna_qq_csna_provider_callback($provider, $request) {
  if (isset($request['code'])) {
    $parameters = array(
      'client_id' => $provider['key'],
      'client_secret' => $provider['secret'],
      'grant_type' => 'authorization_code',
      'redirect_uri' => $provider['callback'],
      'code' => $request['code'],
    );

    $param_data = array(
      'method' => 'POST',
      'data' => drupal_http_build_query($parameters),
    );

    $http = drupal_http_request(url($provider['access_token_uri'], array('query' => $parameters)), $param_data);
    $data = explode('&', $http->data);
    $data = explode('=', reset($data));
    $http = drupal_http_request('https://graph.qq.com/oauth2.0/me?' . $http->data);
    preg_match('/\{[^\}]*\}/', $http->data, $obj);
    $openid = json_decode($obj[0]);
    $http   = drupal_http_request(url($provider['info_uri'], array(
      'query' => array(
        'access_token' => $data[1],
        'oauth_consumer_key' => $provider['key'],
        'openid' => $openid->openid,))));
    $info   = json_decode($http->data);
    return array(
      'access_token' => $data[1],
      'uid' => $openid->openid,
      'name' => $info->nickname,
      'avatar_link' => $info->figureurl_qq_2,
    );
  }
}