Authored by Rock Zhang

第三方登录,找回密码功能添加

Showing 30 changed files with 2355 additions and 35 deletions
<?php
namespace LibModels\Wap\Category;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
use Api\Yohobuy;
use Api\Sign;
/**
* 品牌数据接口操作类
*
* @name BrandData
* @package Library/LibModels/wap/Category
* @copyright yoho.inc
* @version 1.0 (2015-10-10)
* @author gtskk <rocky.zhang@yoho.cn>
*/
class BrandData
{
/**
* 获取品牌数据
*
* @param integer $channel 是否,默认1表示是,传值为空是app中用于品牌搜索的数据
*
* @return array 品牌数据
*/
public static function getBrandsData($channel = 1)
{
// 构建必传参数
$param = Yohobuy::param();
$param['method'] = 'app.brand.brandlist';
$param['yh_channel'] = $channel;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 获取品牌页顶部楼层数据
*
* @return array 品牌也顶部楼层数据
*/
public static function getBrandTopData()
{
// 构建必传参数
$param = Yohobuy::param();
$param['content_code'] = 'ce6ac059493ec26241a8cbe0bfa1b17a';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::SERVICE_URL.'operations/api/v5/resource/get', $param);
}
}
... ...
<?php
namespace LibModels\Wap\Category;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
use Api\Yohobuy;
use Api\Sign;
/**
* 品类数据接口操作类
*
* @name ClassData
* @package Library/LibModels/wap/Category
* @copyright yoho.inc
* @version 1.0 (2015-10-10)
* @author gtskk <rocky.zhang@yoho.cn>
*/
class ClassData
{
/**
* 获取品类数据
*
* @return array 品类数据
*/
public static function getClassesData()
{
// 构建必传参数
$param = Yohobuy::param();
$param['method'] = 'app.sort.get';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
}
... ...
<?php
namespace LibModels\Wap\Category;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
use Api\Yohobuy;
use Api\Sign;
/**
* 关注数据接口操作类
*
* @name FocusData
* @package Library/LibModels/wap/Category
* @copyright yoho.inc
* @version 1.0 (2015-10-10)
* @author gtskk <rocky.zhang@yoho.cn>
*/
class FocusData
{
/**
* 获取关注数据
*
* @param integ $uid 用户ID
* @param string $gender 性别
* @param integer $limit 读取数目限制,默认为10
* @param integer $page 读取分页限制,默认为1
* @return array 关注数据
*/
public static function getFocusData($uid, $gender, $limit = 10, $page = 1)
{
// 构建必传参数
$param = Yohobuy::param();
$param['uid'] = $uid;
$param['gender'] = $gender;
$param['limit'] = $limit;
$param['page'] = $page;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::SERVICE_URL.'guang/api/v1/attention/getlist', $param);
}
}
... ...
<?php
namespace LibModels\wap\Home;
namespace LibModels\Wap\Home;
use Api\Yohobuy;
use Api\Sign;
... ...
<?php
namespace LibModels\Wap\Passport;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
use Api\Yohobuy;
use Api\Sign;
/**
* 品类数据接口操作类
*
* @name ClassData
* @package Library/LibModels/wap/Category
* @copyright yoho.inc
* @version 1.0 (2015-10-10)
* @author gtskk <rocky.zhang@yoho.cn>
*/
class ClassData
{
/**
* 获取地区数据
*
* @return array 地区数据
*/
public static function getAreasData()
{
// 构建必传参数
$param = Yohobuy::param();
$param['method'] = 'app.passport.getArea';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 通过手机号发送验证码找回密码
*
* @param string $mobile 手机号
* @param integer $area 地区码ID
* @return array 返回状态数据
*/
public static function sendCodeToMobile($mobile, $area = 86)
{
// 构建必传参数
$param = Yohobuy::param();
$param['mobile'] = $mobile;
$param['method'] = 'app.register.sendBackpwdCodeToMobile';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
}
... ...
<?php
namespace LibModels\wap\Product;
namespace LibModels\Wap\Product;
use Api\Yohobuy;
use Api\Sign;
... ...
<?php
namespace Plugin\Partner;
isset($_SESSION) || session_start();
defined('DS') || define('DS', '/');
/**
* 抽象类: 第三方接口都会继承该类
*
* @name Factory
* @package library/Plugin/Partner
* @copyright yoho.inc
* @version 1.0 (2015-10-10 17:11:10)
* @author fei.hong <fei.hong@yoho.cn>
*/
abstract class Factory
{
/**
* 接口名称
*
* @var string
*/
protected $apiName = '';
/**
* 接口配置
*
* @var array
*/
protected $apiConfig = array();
/**
* 接口对象
*
* @var array
*/
protected static $apiObjs = array();
/**
* 单例模式: 实例化需要调用的接口对象
*
* @param string $apiName 接口名称
* @return object
*/
public static function create($apiName)
{
$apiName = strtolower($apiName);
if (!isset(self::$apiObjs[$apiName]))
{
// require dirname(__FILE__) . DS . $apiName . DS . 'Call.class.php';
$apiNameCase = ucfirst($apiName);
$apiClass = "Plugin\Partner\\{$apiNameCase}\\Call";
self::$apiObjs[$apiName] = new $apiClass();
self::$apiObjs[$apiName]->apiName = $apiName;
self::$apiObjs[$apiName]->configure();
self::$apiObjs[$apiName]->init();
}
return self::$apiObjs[$apiName];
}
/**
* 应用的配置
*
* @return void
*/
protected function configure()
{
$this->apiConfig = require(dirname(__FILE__) . DS . $this->apiName . DS . 'Config.inc.php');
}
/**初始化*/
abstract protected function init();
/**获取接口*/
abstract public function getAuthorizeUrl();
abstract public function getAccessToken();
abstract public function getUserInfo($token);
abstract public function getFriends($token, $params);
/**同步分享*/
abstract public function syncShare($token, $content, $image, $link);
}
\ No newline at end of file
... ...
<?php
namespace Plugin\Partner\Alipay;
use Plugin\Partner\Factory;
define('TB_CLASS_PATH', dirname(__FILE__).'/class');
require TB_CLASS_PATH . '/lib/alipay.function.php';
require TB_CLASS_PATH . '/AlipaySubmit.class.php';
require TB_CLASS_PATH . '/AlipayNotify.class.php';
/**
* 支付宝快捷的调用接口
*
* @name Call
* @package Plugin/Partner/alipay
* @copyright yoho.inc
* @version 1.0 (2015-10-10 17:56:42)
* @author fei.hong <fei.hong@yoho.cn>
*/
class Call extends Factory
{
protected $alipaySubmit;
protected $alipayNotify;
/**
* 初始化
*/
protected function init()
{
$this->alipaySubmit = new \AlipaySubmit($this->apiConfig);
$this->alipayNotify = new \AlipayNotify($this->apiConfig);
}
/**
* 获取授权URL
*
* @return string
*/
public function getAuthorizeUrl()
{
$parameter = array(
'service' => 'alipay.auth.authorize',
'partner' => $this->apiConfig['partner'],
'target_service' => 'user.auth.quick.login',
'return_url' => $this->apiConfig['return_url'],
'anti_phishing_key' => $this->alipaySubmit->query_timestamp(),
'exter_invoke_ip' => '',
'_input_charset' => $this->apiConfig['input_charset']
);
echo '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>支付宝快捷登录</title></head><body>',
$this->alipaySubmit->buildRequestForm($parameter, 'get'),
'</body></html>';
exit();
}
/**
* 获取授权的TOKEN
*
* @return array
*/
public function getAccessToken()
{
$token = array();
$verify = $this->alipayNotify->verifyReturn();
if ($verify)
{
$token['access_token'] = isset($_GET['token']) ? $_GET['token'] : null;
$token['user_id'] = isset($_GET['user_id']) ? $_GET['user_id'] : null;
}
return $token;
}
/**
* 获取当前用户的基本资料
*
* @param array $token 授权成功的TOKEN, 默认为NULL
* @return array
*/
public function getUserInfo($token)
{
$parameter = array(
'_input_charset' => $this->apiConfig['input_charset'],
'service' => 'mobile.common.login.userInfo.query',
'partner' => $this->apiConfig['partner'],
'token' => $token,
'timestamp' => date('Y-m-d H:i:s'),
);
$result = $this->alipaySubmit->getUserInfoByToken($parameter, $token);
return $result;
}
/**
* 获取当前用户的偶像(关注)列表
*
* 备注:此接口暂未开放
*
* @param array $token 访问令牌
* @param array $params 参数列表
* @return array
*/
public function getFriends($token, $params)
{
return array();
}
/**
* 同步分享
*
* 备注:此接口暂未开放
*
* @param object $token 访问令牌
* @param String $image 新鲜事图片地址
* @param String $content 新鲜事主体内容 注意:最多200个字符。
* @param String $link 新鲜事标题和图片指向的链接
* @return Long 发布新鲜事的ID
*/
public function syncShare($token, $content, $image, $link)
{
return true;
}
}
\ No newline at end of file
... ...
<?php
defined('SITE_MAIN') || define('SITE_MAIN', $_SERVER['HTTP_HOST']);
return array(
// 合作身份者id,以2088开头的16位纯数字
'partner' => '2088701661478015',
// 安全检验码,以数字和字母组成的32位字符
'key' => 'kcxawi9bb07mzh0aq2wcirsf9znusobw',
// 签名方式,不需要修改
'sign_type' => 'MD5',
// 字符编码格式 目前支持 gbk 或 utf-8
'input_charset' => 'utf-8',
// ca证书路径地址,用于curl中ssl校验 (请保证cacert.pem文件在当前文件夹目录中)
'cacert' => dirname(__FILE__) .'/cacert.pem',
// 访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http
'transport' => 'http',
// 页面跳转同步通知页面路径 (需http://格式的完整路径,不允许加?id=123这类自定义参数)
'return_url' => SITE_MAIN . '/passport/sso/partnercallback/partner/alipay',
);
... ...
This diff could not be displayed because it is too large.
<?php
/**
* 支付宝通知处理类
*
* 调试通知返回时,可查看或改写log日志的写入TXT里的数据,来检查通知返回是否正常
*
* @name AlipayNotify
* @package lib/partner/alipay
* @copyright yoho.inc
* @version 5.0 (2014-03-06 16:41:20)
* @author fei.hong <fei.hong@yoho.cn>
*/
class AlipayNotify {
/**
* HTTPS形式消息验证地址
*/
var $https_verify_url = 'https://mapi.alipay.com/gateway.do?service=notify_verify&';
/**
* HTTP形式消息验证地址
*/
var $http_verify_url = 'http://notify.alipay.com/trade/notify_query.do?';
/**
* 支付宝配置
*/
var $alipay_config = array();
function __construct($alipay_config){
$this->alipay_config = $alipay_config;
}
function AlipayNotify($alipay_config) {
$this->__construct($alipay_config);
}
/**
* 针对notify_url验证消息是否是支付宝发出的合法消息
* @return 验证结果
*/
function verifyNotify(){
if (empty($_POST)) { //判断POST来的数组是否为空
return false;
} else {
//生成签名结果
$isSign = $this->getSignVeryfy($_POST, $_POST["sign"]);
//获取支付宝远程服务器ATN结果(验证是否是支付宝发来的消息)
$responseTxt = 'true';
if (! empty($_POST["notify_id"])) {$responseTxt = $this->getResponse($_POST["notify_id"]);}
//写日志记录
//if ($isSign) {
// $isSignStr = 'true';
//}
//else {
// $isSignStr = 'false';
//}
//$log_text = "responseTxt=".$responseTxt."\n notify_url_log:isSign=".$isSignStr.",";
//$log_text = $log_text.createLinkString($_POST);
//logResult($log_text);
//验证
//$responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
//isSign的结果不是true,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
if (preg_match("/true$/i",$responseTxt) && $isSign) {
return true;
} else {
return false;
}
}
}
/**
* 针对return_url验证消息是否是支付宝发出的合法消息
* @return 验证结果
*/
function verifyReturn(){
if(empty($_GET)) {//判断POST来的数组是否为空
return false;
}
else {
//生成签名结果
$isSign = $this->getSignVeryfy($_GET, $_GET["sign"]);
//获取支付宝远程服务器ATN结果(验证是否是支付宝发来的消息)
$responseTxt = 'true';
if (! empty($_GET["notify_id"])) {$responseTxt = $this->getResponse($_GET["notify_id"]);}
//写日志记录
//if ($isSign) {
// $isSignStr = 'true';
//}
//else {
// $isSignStr = 'false';
//}
//$log_text = "responseTxt=".$responseTxt."\n return_url_log:isSign=".$isSignStr.",";
//$log_text = $log_text.createLinkString($_GET);
//logResult($log_text);
//验证
//$responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
//isSign的结果不是true,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
if (preg_match("/true$/i",$responseTxt) && $isSign) {
return true;
} else {
return false;
}
}
}
/**
* 获取返回时的签名验证结果
* @param $para_temp 通知返回来的参数数组
* @param $sign 返回的签名结果
* @return 签名验证结果
*/
function getSignVeryfy($para_temp, $sign) {
//除去待签名参数数组中的空值和签名参数
$para_filter = paraFilter($para_temp);
//对待签名参数数组排序
$para_sort = argSort($para_filter);
//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
$prestr = createLinkstring($para_sort);
$isSgin = false;
switch ($this->alipay_config['sign_type']) {
case "MD5" :
$isSgin = md5Verify($prestr, $sign, $this->alipay_config['key']);
break;
default :
$isSgin = false;
}
return $isSgin;
}
/**
* 获取远程服务器ATN结果,验证返回URL
* @param $notify_id 通知校验ID
* @return 服务器ATN结果
* 验证结果集:
* invalid命令参数不对 出现这个错误,请检测返回处理中partner和key是否为空
* true 返回正确信息
* false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟
*/
function getResponse($notify_id) {
$transport = $this->alipay_config['transport'];
$partner = $this->alipay_config['partner'];
$veryfy_url = '';
if($transport == 'https') {
$veryfy_url = $this->https_verify_url;
}
else {
$veryfy_url = $this->http_verify_url;
}
$veryfy_url = $veryfy_url."partner=" . $partner . "&notify_id=" . $notify_id;
$responseTxt = getHttpResponseGET($veryfy_url, $this->alipay_config['cacert']);
return $responseTxt;
}
}
?>
... ...
<?php
/**
* 支付宝各接口请求提交类
*
* @name AlipaySubmit
* @package lib/partner/alipay
* @copyright yoho.inc
* @version 5.0 (2014-03-06 16:23:47)
* @author fei.hong <fei.hong@yoho.cn>
*/
class AlipaySubmit {
/**
* 支付宝配置
*/
var $alipay_config = array();
/**
* 支付宝网关地址(新)
*/
var $alipay_gateway_new = 'https://mapi.alipay.com/gateway.do?';
function __construct($alipay_config){
$this->alipay_config = $alipay_config;
}
function AlipaySubmit($alipay_config) {
$this->__construct($alipay_config);
}
/**
* 生成签名结果
* @param $para_sort 已排序要签名的数组
* return 签名结果字符串
*/
function buildRequestMysign($para_sort) {
//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
$prestr = createLinkstring($para_sort);
$mysign = '';
switch ($this->alipay_config['sign_type']) {
case 'MD5' :
$mysign = md5Sign($prestr, $this->alipay_config['key']);
break;
default :
$mysign = '';
}
return $mysign;
}
/**
* 生成要请求给支付宝的参数数组
* @param $para_temp 请求前的参数数组
* @return 要请求的参数数组
*/
function buildRequestPara($para_temp) {
//除去待签名参数数组中的空值和签名参数
$para_filter = paraFilter($para_temp);
//对待签名参数数组排序
$para_sort = argSort($para_filter);
//生成签名结果
$mysign = $this->buildRequestMysign($para_sort);
//签名结果与签名方式加入请求提交参数组中
$para_sort['sign'] = $mysign;
$para_sort['sign_type'] = $this->alipay_config['sign_type'];
return $para_sort;
}
/**
* 生成要请求给支付宝的参数数组
* @param $para_temp 请求前的参数数组
* @return 要请求的参数数组字符串
*/
function buildRequestParaToString($para_temp) {
//待请求参数数组
$para = $this->buildRequestPara($para_temp);
//把参数组中所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对字符串做urlencode编码
$request_data = createLinkstringUrlencode($para);
return $request_data;
}
/**
* 建立请求,以表单HTML形式构造(默认)
* @param $para_temp 请求参数数组
* @param $method 提交方式。两个值可选:post、get
* @param $button_name 确认按钮显示文字
* @return 提交表单HTML文本
*/
function buildRequestForm($para_temp, $method) {
//待请求参数数组
$para = $this->buildRequestPara($para_temp);
$sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='".$this->alipay_gateway_new."_input_charset=".$this->alipay_config['input_charset']."' method='".$method."'>";
while (list ($key, $val) = each ($para)) {
$sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
}
$sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
return $sHtml;
}
/**
* 建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果
* @param $para_temp 请求参数数组
* @return 支付宝处理结果
*/
function buildRequestHttp($para_temp) {
$sResult = '';
//待请求参数数组字符串
$request_data = $this->buildRequestPara($para_temp);
//远程获取数据
$sResult = getHttpResponsePOST($this->alipay_gateway_new, $this->alipay_config['cacert'],$request_data,$this->alipay_config['input_charset']);
return $sResult;
}
/**
* 建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果,带文件上传功能
* @param $para_temp 请求参数数组
* @param $file_para_name 文件类型的参数名
* @param $file_name 文件完整绝对路径
* @return 支付宝返回处理结果
*/
function buildRequestHttpInFile($para_temp, $file_para_name, $file_name) {
//待请求参数数组
$para = $this->buildRequestPara($para_temp);
$para[$file_para_name] = "@".$file_name;
//远程获取数据
$sResult = getHttpResponsePOST($this->alipay_gateway_new, $this->alipay_config['cacert'],$para,$this->alipay_config['input_charset']);
return $sResult;
}
/**
* 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数
* 注意:该功能PHP5环境及以上支持,因此必须服务器、本地电脑中装有支持DOMDocument、SSL的PHP配置环境。建议本地调试时使用PHP开发软件
* return 时间戳字符串
*/
function query_timestamp() {
$url = $this->alipay_gateway_new."service=query_timestamp&partner=".$this->alipay_config['partner']."&_input_charset=".$this->alipay_config['input_charset'];
$encrypt_key = "";
$doc = new DOMDocument();
$doc->load($url);
$itemEncrypt_key = $doc->getElementsByTagName( "encrypt_key" );
$encrypt_key = $itemEncrypt_key->item(0)->nodeValue;
return $encrypt_key;
}
/**
* 通过token获取用户信息
*
* @param array $parameter 参数项
* @return array
* @since 1.0.3
*/
function getUserInfoByToken($parameter) {
$parameter = $this->buildRequestPara($parameter);
// 系统参数放入GET请求串
$requestUrl = $this->alipay_gateway_new . http_build_query($parameter, null, '&');
// 发起HTTP请求
$result = array();
try {
$response = getHttpResponseGET($requestUrl, $this->alipay_config['cacert']);
if (is_string($response)) {
$result = json_decode(json_encode(simplexml_load_string($response)), true);
}
} catch (Exception $e) {
// do nothing
}
return $result;
}
}
?>
\ No newline at end of file
... ...
<?php
/* *
* 支付宝接口公用函数
* 详细:该类是请求、通知返回两个文件所调用的公用函数核心处理文件
* 版本:3.3
* 日期:2012-07-19
* 说明:
* 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
* 该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
/**
* 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
* @param $para 需要拼接的数组
* return 拼接完成以后的字符串
*/
function createLinkstring($para) {
$arg = "";
while (list ($key, $val) = each ($para)) {
$arg.=$key."=".$val."&";
}
//去掉最后一个&字符
$arg = substr($arg,0,count($arg)-2);
//如果存在转义字符,那么去掉转义
if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
return $arg;
}
/**
* 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对字符串做urlencode编码
* @param $para 需要拼接的数组
* return 拼接完成以后的字符串
*/
function createLinkstringUrlencode($para) {
$arg = "";
while (list ($key, $val) = each ($para)) {
$arg.=$key."=".urlencode($val)."&";
}
//去掉最后一个&字符
$arg = substr($arg,0,count($arg)-2);
//如果存在转义字符,那么去掉转义
if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
return $arg;
}
/**
* 除去数组中的空值和签名参数
* @param $para 签名参数组
* return 去掉空值与签名参数后的新签名参数组
*/
function paraFilter($para) {
$para_filter = array();
while (list ($key, $val) = each ($para)) {
if($key == "sign" || $key == "sign_type" || $val == "")continue;
else $para_filter[$key] = $para[$key];
}
return $para_filter;
}
/**
* 对数组排序
* @param $para 排序前的数组
* return 排序后的数组
*/
function argSort($para) {
ksort($para);
reset($para);
return $para;
}
/**
* 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
* 注意:服务器需要开通fopen配置
* @param $word 要写入日志里的文本内容 默认值:空值
*/
function logResult($word='') {
$fp = fopen("log.txt","a");
flock($fp, LOCK_EX) ;
fwrite($fp,"执行日期:".strftime("%Y%m%d%H%M%S",time())."\n".$word."\n");
flock($fp, LOCK_UN);
fclose($fp);
}
/**
* 远程获取数据,POST模式
* 注意:
* 1.使用Crul需要修改服务器中php.ini文件的设置,找到php_curl.dll去掉前面的";"就行了
* 2.文件夹中cacert.pem是SSL证书请保证其路径有效,目前默认路径是:getcwd().'\\cacert.pem'
* @param $url 指定URL完整路径地址
* @param $cacert_url 指定当前工作目录绝对路径
* @param $para 请求的数据
* @param $input_charset 编码格式。默认值:空值
* return 远程输出的数据
*/
function getHttpResponsePOST($url, $cacert_url, $para, $input_charset = '') {
if (trim($input_charset) != '') {
$url = $url."_input_charset=".$input_charset;
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
curl_setopt($curl,CURLOPT_POST,true); // post传输数据
curl_setopt($curl,CURLOPT_POSTFIELDS,$para);// post传输数据
$responseText = curl_exec($curl);
//var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
curl_close($curl);
return $responseText;
}
/**
* 远程获取数据,GET模式
* 注意:
* 1.使用Crul需要修改服务器中php.ini文件的设置,找到php_curl.dll去掉前面的";"就行了
* 2.文件夹中cacert.pem是SSL证书请保证其路径有效,目前默认路径是:getcwd().'\\cacert.pem'
* @param $url 指定URL完整路径地址
* @param $cacert_url 指定当前工作目录绝对路径
* return 远程输出的数据
*/
function getHttpResponseGET($url,$cacert_url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
$responseText = curl_exec($curl);
//var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
curl_close($curl);
return $responseText;
}
/**
* 实现多种字符编码方式
* @param $input 需要编码的字符串
* @param $_output_charset 输出的编码格式
* @param $_input_charset 输入的编码格式
* return 编码后的字符串
*/
function charsetEncode($input,$_output_charset ,$_input_charset) {
$output = "";
if(!isset($_output_charset) )$_output_charset = $_input_charset;
if($_input_charset == $_output_charset || $input ==null ) {
$output = $input;
} elseif (function_exists("mb_convert_encoding")) {
$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
} elseif(function_exists("iconv")) {
$output = iconv($_input_charset,$_output_charset,$input);
} else die("sorry, you have no libs support for charset change.");
return $output;
}
/**
* 实现多种字符解码方式
* @param $input 需要解码的字符串
* @param $_output_charset 输出的解码格式
* @param $_input_charset 输入的解码格式
* return 解码后的字符串
*/
function charsetDecode($input,$_input_charset ,$_output_charset) {
$output = "";
if(!isset($_input_charset) )$_input_charset = $_input_charset ;
if($_input_charset == $_output_charset || $input ==null ) {
$output = $input;
} elseif (function_exists("mb_convert_encoding")) {
$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
} elseif(function_exists("iconv")) {
$output = iconv($_input_charset,$_output_charset,$input);
} else die("sorry, you have no libs support for charset changes.");
return $output;
}
/** MD5加密 **/
/**
* 签名字符串
* @param $prestr 需要签名的字符串
* @param $key 私钥
* return 签名结果
*/
function md5Sign($prestr, $key) {
$prestr = $prestr . $key;
return md5($prestr);
}
/**
* 验证签名
* @param $prestr 需要签名的字符串
* @param $sign 签名结果
* @param $key 私钥
* return 签名结果
*/
function md5Verify($prestr, $sign, $key) {
$prestr = $prestr . $key;
$mysgin = md5($prestr);
if($mysgin == $sign) {
return true;
}
else {
return false;
}
}
?>
\ No newline at end of file
... ...
集成时请注意:
本文件log.txt请不要删除。
该文本用于写日志函数。
... ...
╭───────────────────────╮
────┤ 支付宝代码示例结构说明 ├────
╰───────────────────────╯
 
  接口名称:支付宝快捷登录接口(alipay.auth.authorize)
    代码版本:3.3
开发语言:PHP
版 权:支付宝(中国)网络技术有限公司
  制 作 者:支付宝商户事业部技术支持组
联系方式:商户服务电话0571-88158090
─────────────────────────────────
───────
代码文件结构
───────
alipay.auth.authorize-php-UTF-8
├lib┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈类文件夹
│ │
│ ├alipay_core.function.php ┈┈┈┈┈┈支付宝接口公用函数文件
│ │
│ ├alipay_notify.class.php┈┈┈┈┈┈┈支付宝通知处理类文件
│ │
│ ├alipay_submit.class.php┈┈┈┈┈┈┈支付宝各接口请求提交类文件
│ │
│ └alipay_md5.function.php┈┈┈┈┈┈┈支付宝接口MD5函数文件
├log.txt┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈日志文件
├alipay.config.php┈┈┈┈┈┈┈┈┈┈┈┈基础配置类文件
├alipayapi.php┈┈┈┈┈┈┈┈┈┈┈┈┈┈支付宝接口入口文件
├return_url.php ┈┈┈┈┈┈┈┈┈┈┈┈┈页面跳转同步通知文件
├cacert.pem ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈用于CURL中校验SSL的CA证书文件
└readme.txt ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈使用说明文本
※注意※
1、必须开启curl服务
(1)使用Crul需要修改服务器中php.ini文件的设置,找到php_curl.dll去掉前面的";"即可
(2)文件夹中cacert.pem文件请务必放置到商户网站平台中(如:服务器上),并且保证其路径有效,提供的代码demo中的默认路径是当前文件夹下——getcwd().'\\cacert.pem'
2、需要配置的文件是:
alipay.config.php
alipayapi.php
●本代码示例(DEMO)采用fsockopen()的方法远程HTTP获取数据、采用DOMDocument()的方法解析XML数据。
请根据商户网站自身情况来决定是否使用代码示例中的方式——
如果不使用fsockopen,那么建议用curl来代替;
如果环境不是PHP5版本或其以上,那么请用其他方法代替DOMDocument()。
curl、XML解析方法需您自行编写代码。
─────────
类文件函数结构
─────────
alipay_core.function.php
function createLinkstring($para)
功能:把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
输入:Array $para 需要拼接的数组
输出:String 拼接完成以后的字符串
function createLinkstringUrlencode($para)
功能:把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对参数值urlencode
输入:Array $para 需要拼接的数组
输出:String 拼接完成以后的字符串
function paraFilter($para)
功能:除去数组中的空值和签名参数
输入:Array $para 签名参数组
输出:Array 去掉空值与签名参数后的新签名参数组
function argSort($para)
功能:对数组排序
输入:Array $para 排序前的数组
输出:Array 排序后的数组
function logResult($word='')
功能:写日志,方便测试(看网站需求,也可以改成存入数据库)
输入:String $word 要写入日志里的文本内容 默认值:空值
function getHttpResponsePOST($url, $cacert_url, $para, $input_charset = '')
功能:远程获取数据,POST模式
输入:String $url 指定URL完整路径地址
String $cacert_url 指定当前工作目录绝对路径
Array $para 请求的数据
String $input_charset 编码格式。默认值:空值
输出:String 远程输出的数据
function getHttpResponseGET($url, $cacert_url)
功能:远程获取数据,GET模式
输入:String $url 指定URL完整路径地址
String $cacert_url 指定当前工作目录绝对路径
输出:String 远程输出的数据
function charsetEncode($input,$_output_charset ,$_input_charset)
功能:实现多种字符编码方式
输入:String $input 需要编码的字符串
String $_output_charset 输出的编码格式
String $_input_charset 输入的编码格式
输出:String 编码后的字符串
function charsetDecode($input,$_input_charset ,$_output_charset)
功能:实现多种字符解码方式
输入:String $input 需要解码的字符串
String $_output_charset 输出的解码格式
String $_input_charset 输入的解码格式
输出:String 解码后的字符串
┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉
function md5Sign($prestr, $key)
功能:MD5签名
输入:String $prestr 待签名数据
String $key 私钥
输出:String 签名结果
function md5Verify($prestr, $sign, $key)
功能:MD5验签
输入:String $data 待签名数据
String $sign 签名结果
String $key 私钥
输出:bool 验证结果
┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉
alipay_notify.class.php
function verifyNotify()
功能:对notify_url的认证
输出:Bool 验证结果:true/false
function verifyReturn()
功能:对return_url的认证
输出:Bool 验证结果:true/false
function getSignVeryfy($para_temp, $sign)
功能:获取返回时的签名验证结果
输入:Array $para_temp 通知返回来的参数数组
String $sign 支付宝返回的签名结果
输出:Bool 获得签名验证结果
function getResponse($notify_id)
功能:获取远程服务器ATN结果,验证返回URL
输入:String $notify_id 通知校验ID
输出:String 服务器ATN结果
┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉
alipay_submit.class.php
function buildRequestMysign($para_sort)
功能:生成要请求给支付宝的参数数组
输入:Array $para_sort 已排序要签名的数组
输出:String 签名结果
function buildRequestPara($para_temp)
功能:根据反馈回来的信息,生成签名结果
输入:Array $para_temp 请求前的参数数组
输出:String 要请求的参数数组
function buildRequestParaToString($para_temp)
功能:根据反馈回来的信息,生成签名结果
输入:Array $para_temp 请求前的参数数组
输出:String 要请求的参数数组字符串
function buildRequestForm($para_temp, $method, $button_name)
功能:建立请求,以表单HTML形式构造(默认)
输入:Array $para_temp 请求前的参数数组
String $method 提交方式。两个值可选:post、get
String $button_name 确认按钮显示文字
输出:String 提交表单HTML文本
function buildRequestHttp($para_temp)
功能:建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果
输入:Array $para_temp 请求前的参数数组
输出:String 支付宝处理结果
function buildRequestHttpInFile($para_temp, $file_para_name, $file_name)
功能:建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果,带文件上传功能
输入:Array $para_temp 请求参数数组
String $file_para_name 文件类型的参数名
String $file_name 文件完整绝对路径
输出:String 支付宝返回处理结果
function query_timestamp()
功能:用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数
输出:String 时间戳字符串
┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉┉
──────────
出现问题,求助方法
──────────
如果在集成支付宝接口时,有疑问或出现问题,可使用下面的链接,提交申请。
https://b.alipay.com/support/helperApply.htm?action=supportHome
我们会有专门的技术支持人员为您处理
... ...
<?php
namespace Plugin\Partner\Qqconnect;
use Plugin\Partner\Factory;
define('QC_CLASS_PATH', dirname (__FILE__) . '/class/');
require QC_CLASS_PATH . 'QC.class.php';
/**
* 腾讯QQ互联的调用接口
*
* @name Call
* @package lib/partner/qqconnect
* @copyright yoho.inc
* @version 4.0 (2013-12-19 11:42:11)
* @author fei.hong <fei.hong@yoho.cn>
*/
class Call extends Factory
{
/*QQ互联对象*/
protected $qc;
/**
* 初始化
*/
protected function init()
{
$this->qc = new \QC();
}
/**
* 获取授权URL
*
* @return string
*/
public function getAuthorizeUrl()
{
return $this->qc->qq_login();
}
/**
* 获取授权的TOKEN
*
* @return array
*/
public function getAccessToken()
{
$token = array();
try
{
$token = $this->qc->qq_callback();
$token['openid'] = $this->qc->get_openid();
}
catch (Exception $e)
{
// do nothing
}
return $token;
}
/**
* 获取当前用户的基本资料
*
* @param array $token 授权成功的TOKEN, 默认为NULL
* @return array
*/
public function getUserInfo($token)
{
$userInfo = array();
if (is_array($token) && isset($token['openid']))
{
$this->qc = new QC($token['access_token'], $token['openid']);
$userInfo = $this->qc->get_user_info();
if (isset($userInfo['ret']) && $userInfo['ret'] != 0)
{
$userInfo = array();
}
}
return $userInfo;
}
/**
* 获取当前用户的偶像(关注)列表
*
* @see http://wiki.connect.qq.com/get_idollist
* @param string $access_token 访问令牌
* @param string $openid 腾讯唯一的对应QQ号
* @param array $params 参数列表
* format 是 返回数据的格式(json或xml)
* reqnum 是 请求个数(1-30)
* startindex 是 起始位置(第一页:填0,继续向下翻页:填上次请求返回的nextstartpos)
* mode 是 获取模式,默认为0
* mode=0,新粉丝在前,只能拉取1000个
* mode=1,最多可拉取一万粉丝,暂不支持排序
* install 否 过滤安装应用好友(可选)
* 0-不考虑该参数,1-获取已安装应用好友,2-获取未安装应用好友
* sex 否 按性别过滤标识,1-男,2-女,0-不进行性别过滤,默认为0,支持排序
* @return array
*/
public function getFriends($token, $params)
{
$friends = array();
if (is_array($token) && isset($token['openid']))
{
$this->qc = new QC($token['access_token'], $token['openid']);
$friends = $this->qc->get_idollist($params);
if (isset($friends['ret']) && $friends['ret'] != 0)
{
$friends = array();
}
}
return $friends;
}
/**
* 同步分享
*
* @param array $token 授权成功的TOKEN
* @param string $content 要更新的微博信息。信息内容不超过140个汉字, 为空返回400错误。
* @param string $image 要发布的图片路径, 支持url。[只支持png/jpg/gif三种格式, 增加格式请修改get_image_mime方法]
* @param string $link URL地址, 通过该地址链接回来
* @return boolean false:失败, true:成功
*/
public function syncShare($token, $content, $image, $link)
{
$result = false;
if (is_array($token) && isset($token['openid']))
{
$this->qc = new QC($token['access_token'], $token['openid']);
$param = array('title' => '来自YOHO.CN的分享', 'url' => $link, 'summary' => $content,
'images' => $image, 'site' => 'yoho.cn', 'fromurl' => SITE_MAIN,);
$response = $this->qc->add_share($param);
if (isset($response['ret']) && $response['ret'] == 0)
{
$result = true;
}
}
return $result;
}
}
\ No newline at end of file
... ...
<?php
defined('SITE_MAIN') || define('SITE_MAIN', 'http://www.yoho.cn');
return array(
'appid' => '100229394',
'appkey' => 'c0af9c29e0900813028c2ccb42021792',
'callback' => SITE_MAIN . '/passport/sso/partnercallback/partner/qqconnect',
'scope' => 'get_user_info,add_share,upload_pic,get_idollist,get_fanslist',
'errorReport' => false,
);
\ No newline at end of file
... ...
<?php
/* PHP SDK
* @version 2.0.0
* @author connect@qq.com
* @copyright © 2013, Tencent Corporation. All rights reserved.
*/
require_once(QC_CLASS_PATH.'Recorder.class.php');
/*
* @brief ErrorCase类,封闭异常
* */
class ErrorCase{
private $errorMsg;
public function __construct(){
$this->errorMsg = array(
"20001" => "<h2>配置文件损坏或无法读取,请重新执行intall</h2>",
"30001" => "<h2>The state does not match. You may be a victim of CSRF.</h2>",
"50001" => "<h2>可能是服务器无法请求https协议</h2>可能未开启curl支持,请尝试开启curl支持,重启web服务器,如果问题仍未解决,请联系我们"
);
}
/**
* showError
* 显示错误信息
* @param int $code 错误代码
* @param string $description 描述信息(可选)
*/
public function showError($code, $description = '$'){
$recorder = new Recorder();
if(! $recorder->readInc("errorReport")){
die();//die quietly
}
echo "<meta charset=\"UTF-8\">";
if($description == "$"){
die($this->errorMsg[$code]);
}else{
echo "<h3>error:</h3>$code";
echo "<h3>msg :</h3>$description";
exit();
}
}
public function showTips($code, $description = '$'){
}
}
... ...
<?php
/* PHP SDK
* @version 2.0.0
* @author connect@qq.com
* @copyright © 2013, Tencent Corporation. All rights reserved.
*/
require_once(QC_CLASS_PATH.'Recorder.class.php');
require_once(QC_CLASS_PATH.'URL.class.php');
require_once(QC_CLASS_PATH.'ErrorCase.class.php');
class Oauth{
const VERSION = "2.0";
const GET_AUTH_CODE_URL = "https://graph.qq.com/oauth2.0/authorize";
const GET_ACCESS_TOKEN_URL = "https://graph.qq.com/oauth2.0/token";
const GET_OPENID_URL = "https://graph.qq.com/oauth2.0/me";
protected $recorder;
public $urlUtils;
protected $error;
function __construct(){
$this->recorder = new Recorder();
$this->urlUtils = new URL();
$this->error = new ErrorCase();
}
public function qq_login(){
$appid = $this->recorder->readInc("appid");
$callback = $this->recorder->readInc("callback");
$scope = $this->recorder->readInc("scope");
//-------生成唯一随机串防CSRF攻击
$state = md5(uniqid(rand(), TRUE));
// $this->recorder->write('state',$state);
$_SESSION['qqstate'] = $state;
//-------构造请求参数列表
$keysArr = array(
"response_type" => "code",
"client_id" => $appid,
"redirect_uri" => $callback,
"state" => $state,
"scope" => $scope
);
$login_url = $this->urlUtils->combineURL(self::GET_AUTH_CODE_URL, $keysArr);
header("Location:$login_url");
}
public function qq_callback(){
$state = $this->recorder->read("state");
//--------验证state防止CSRF攻击
// if($_GET['state'] != $state){
if ($_GET['state'] != $_SESSION['qqstate']) {
$this->error->showError("30001");
}
//-------请求参数列表
$keysArr = array(
"grant_type" => "authorization_code",
"client_id" => $this->recorder->readInc("appid"),
"redirect_uri" => urlencode($this->recorder->readInc("callback")),
"client_secret" => $this->recorder->readInc("appkey"),
"code" => $_GET['code']
);
//------构造请求access_token的url
$token_url = $this->urlUtils->combineURL(self::GET_ACCESS_TOKEN_URL, $keysArr);
$response = $this->urlUtils->get_contents($token_url);
if(strpos($response, "callback") !== false){
$lpos = strpos($response, "(");
$rpos = strrpos($response, ")");
$response = substr($response, $lpos + 1, $rpos - $lpos -1);
$msg = json_decode($response);
if(isset($msg->error)){
$this->error->showError($msg->error, $msg->error_description);
}
}
$params = array();
parse_str($response, $params);
$this->recorder->write("access_token", $params["access_token"]);
// return $params["access_token"];
// 根据业务需要改造了一下
return $params;
}
public function get_openid(){
//-------请求参数列表
$keysArr = array(
"access_token" => $this->recorder->read("access_token")
);
$graph_url = $this->urlUtils->combineURL(self::GET_OPENID_URL, $keysArr);
$response = $this->urlUtils->get_contents($graph_url);
//--------检测错误是否发生
if(strpos($response, "callback") !== false){
$lpos = strpos($response, "(");
$rpos = strrpos($response, ")");
$response = substr($response, $lpos + 1, $rpos - $lpos -1);
}
$user = json_decode($response);
if(isset($user->error)){
$this->error->showError($user->error, $user->error_description);
}
//------记录openid
$this->recorder->write("openid", $user->openid);
return $user->openid;
}
}
... ...
<?php
/* PHP SDK
* @version 2.0.0
* @author connect@qq.com
* @copyright © 2013, Tencent Corporation. All rights reserved.
*/
require_once(QC_CLASS_PATH.'Oauth.class.php');
/*
* @brief QC类,api外部对象,调用接口全部依赖于此对象
* */
class QC extends Oauth{
private $kesArr, $APIMap;
/**
* _construct
*
* 构造方法
* @access public
* @since 5
* @param string $access_token access_token value
* @param string $openid openid value
* @return Object QC
*/
public function __construct($access_token = "", $openid = ""){
parent::__construct();
//如果access_token和openid为空,则从session里去取,适用于demo展示情形
if($access_token === "" || $openid === ""){
$this->keysArr = array(
"oauth_consumer_key" => (int)$this->recorder->readInc("appid"),
"access_token" => $this->recorder->read("access_token"),
"openid" => $this->recorder->read("openid")
);
}else{
$this->keysArr = array(
"oauth_consumer_key" => (int)$this->recorder->readInc("appid"),
"access_token" => $access_token,
"openid" => $openid
);
}
//初始化APIMap
/*
* 加#表示非必须,无则不传入url(url中不会出现该参数), "key" => "val" 表示key如果没有定义则使用默认值val
* 规则 array( baseUrl, argListArr, method)
*/
$this->APIMap = array(
/* qzone */
"add_blog" => array(
"https://graph.qq.com/blog/add_one_blog",
array("title", "format" => "json", "content" => null),
"POST"
),
"add_topic" => array(
"https://graph.qq.com/shuoshuo/add_topic",
array("richtype","richval","con","#lbs_nm","#lbs_x","#lbs_y","format" => "json", "#third_source"),
"POST"
),
"get_user_info" => array(
"https://graph.qq.com/user/get_user_info",
array("format" => "json"),
"GET"
),
"add_one_blog" => array(
"https://graph.qq.com/blog/add_one_blog",
array("title", "content", "format" => "json"),
"GET"
),
"add_album" => array(
"https://graph.qq.com/photo/add_album",
array("albumname", "#albumdesc", "#priv", "format" => "json"),
"POST"
),
"upload_pic" => array(
"https://graph.qq.com/photo/upload_pic",
array("picture", "#photodesc", "#title", "#albumid", "#mobile", "#x", "#y", "#needfeed", "#successnum", "#picnum", "format" => "json"),
"POST"
),
"list_album" => array(
"https://graph.qq.com/photo/list_album",
array("format" => "json")
),
"add_share" => array(
"https://graph.qq.com/share/add_share",
array("title", "url", "#comment","#summary","#images","format" => "json","#type","#playurl","#nswb","site","fromurl"),
"POST"
),
"check_page_fans" => array(
"https://graph.qq.com/user/check_page_fans",
array("page_id" => "314416946","format" => "json")
),
/* wblog */
"add_t" => array(
"https://graph.qq.com/t/add_t",
array("format" => "json", "content","#clientip","#longitude","#compatibleflag"),
"POST"
),
"add_pic_t" => array(
"https://graph.qq.com/t/add_pic_t",
array("content", "pic", "format" => "json", "#clientip", "#longitude", "#latitude", "#syncflag", "#compatiblefalg"),
"POST"
),
"del_t" => array(
"https://graph.qq.com/t/del_t",
array("id", "format" => "json"),
"POST"
),
"get_repost_list" => array(
"https://graph.qq.com/t/get_repost_list",
array("flag", "rootid", "pageflag", "pagetime", "reqnum", "twitterid", "format" => "json")
),
"get_info" => array(
"https://graph.qq.com/user/get_info",
array("format" => "json")
),
"get_other_info" => array(
"https://graph.qq.com/user/get_other_info",
array("format" => "json", "#name", "fopenid")
),
"get_fanslist" => array(
"https://graph.qq.com/relation/get_fanslist",
array("format" => "json", "reqnum", "startindex", "#mode", "#install", "#sex")
),
"get_idollist" => array(
"https://graph.qq.com/relation/get_idollist",
array("format" => "json", "reqnum", "startindex", "#mode", "#install")
),
"add_idol" => array(
"https://graph.qq.com/relation/add_idol",
array("format" => "json", "#name-1", "#fopenids-1"),
"POST"
),
"del_idol" => array(
"https://graph.qq.com/relation/del_idol",
array("format" => "json", "#name-1", "#fopenid-1"),
"POST"
),
/* pay */
"get_tenpay_addr" => array(
"https://graph.qq.com/cft_info/get_tenpay_addr",
array("ver" => 1,"limit" => 5,"offset" => 0,"format" => "json")
)
);
}
//调用相应api
private function _applyAPI($arr, $argsList, $baseUrl, $method){
$pre = "#";
$keysArr = $this->keysArr;
$optionArgList = array();//一些多项选填参数必选一的情形
foreach($argsList as $key => $val){
$tmpKey = $key;
$tmpVal = $val;
if(!is_string($key)){
$tmpKey = $val;
if(strpos($val,$pre) === 0){
$tmpVal = $pre;
$tmpKey = substr($tmpKey,1);
if(preg_match("/-(\d$)/", $tmpKey, $res)){
$tmpKey = str_replace($res[0], "", $tmpKey);
$optionArgList[$res[1]][] = $tmpKey;
}
}else{
$tmpVal = null;
}
}
//-----如果没有设置相应的参数
if(!isset($arr[$tmpKey]) || $arr[$tmpKey] === ""){
if($tmpVal == $pre){//则使用默认的值
continue;
}else if($tmpVal){
$arr[$tmpKey] = $tmpVal;
}else{
if($v = $_FILES[$tmpKey]){
$filename = dirname($v['tmp_name'])."/".$v['name'];
move_uploaded_file($v['tmp_name'], $filename);
$arr[$tmpKey] = "@$filename";
}else{
$this->error->showError("api调用参数错误","未传入参数$tmpKey");
}
}
}
$keysArr[$tmpKey] = $arr[$tmpKey];
}
//检查选填参数必填一的情形
foreach($optionArgList as $val){
$n = 0;
foreach($val as $v){
if(in_array($v, array_keys($keysArr))){
$n ++;
}
}
if(! $n){
$str = implode(",",$val);
$this->error->showError("api调用参数错误",$str."必填一个");
}
}
if($method == "POST"){
if($baseUrl == "https://graph.qq.com/blog/add_one_blog") $response = $this->urlUtils->post($baseUrl, $keysArr, 1);
else $response = $this->urlUtils->post($baseUrl, $keysArr, 0);
}else if($method == "GET"){
$response = $this->urlUtils->get($baseUrl, $keysArr);
}
return $response;
}
/**
* _call
* 魔术方法,做api调用转发
* @param string $name 调用的方法名称
* @param array $arg 参数列表数组
* @since 5.0
* @return array 返加调用结果数组
*/
public function __call($name,$arg){
//如果APIMap不存在相应的api
if(empty($this->APIMap[$name])){
$this->error->showError("api调用名称错误","不存在的API: <span style='color:red;'>$name</span>");
}
//从APIMap获取api相应参数
$baseUrl = $this->APIMap[$name][0];
$argsList = $this->APIMap[$name][1];
$method = isset($this->APIMap[$name][2]) ? $this->APIMap[$name][2] : "GET";
if(empty($arg)){
$arg[0] = null;
}
//对于get_tenpay_addr,特殊处理,php json_decode对\xA312此类字符支持不好
if($name != "get_tenpay_addr"){
$response = json_decode($this->_applyAPI($arg[0], $argsList, $baseUrl, $method));
$responseArr = $this->objToArr($response);
}else{
$responseArr = $this->simple_json_parser($this->_applyAPI($arg[0], $argsList, $baseUrl, $method));
}
// 根据业务需求,返回结果
//检查返回ret判断api是否成功调用
// if($responseArr['ret'] == 0){
// return $responseArr;
// }else{
// $this->error->showError($response->ret, $response->msg);
// }
return $responseArr;
}
//php 对象到数组转换
private function objToArr($obj){
if(!is_object($obj) && !is_array($obj)) {
return $obj;
}
$arr = array();
foreach($obj as $k => $v){
$arr[$k] = $this->objToArr($v);
}
return $arr;
}
/**
* get_access_token
* 获得access_token
* @param void
* @since 5.0
* @return string 返加access_token
*/
public function get_access_token(){
return $this->recorder->read("access_token");
}
//简单实现json到php数组转换功能
private function simple_json_parser($json){
$json = str_replace("{","",str_replace("}","", $json));
$jsonValue = explode(",", $json);
$arr = array();
foreach($jsonValue as $v){
$jValue = explode(":", $v);
$arr[str_replace('"',"", $jValue[0])] = (str_replace('"', "", $jValue[1]));
}
return $arr;
}
}
... ...
<?php
/* PHP SDK
* @version 2.0.0
* @author connect@qq.com
* @copyright © 2013, Tencent Corporation. All rights reserved.
*/
require_once(QC_CLASS_PATH.'ErrorCase.class.php');
class Recorder{
private static $data;
private $inc;
private $error;
public function __construct(){
$this->error = new ErrorCase();
//-------读取配置文件
$this->inc = require(QC_CLASS_PATH.'../Config.inc.php');
if(empty($this->inc)){
$this->error->showError("20001");
}
if(empty($_SESSION['QC_userData'])){
self::$data = array();
}else{
self::$data = $_SESSION['QC_userData'];
}
}
public function write($name,$value){
self::$data[$name] = $value;
}
public function read($name){
if(empty(self::$data[$name])){
return null;
}else{
return self::$data[$name];
}
}
public function readInc($name){
if(empty($this->inc[$name])){
return null;
}else{
return $this->inc[$name];
}
}
public function delete($name){
unset(self::$data[$name]);
}
function __destruct(){
$_SESSION['QC_userData'] = self::$data;
}
}
... ...
<?php
/* PHP SDK
* @version 2.0.0
* @author connect@qq.com
* @copyright © 2013, Tencent Corporation. All rights reserved.
*/
require_once(QC_CLASS_PATH.'ErrorCase.class.php');
/*
* @brief url封装类,将常用的url请求操作封装在一起
* */
class URL{
private $error;
public function __construct(){
$this->error = new ErrorCase();
}
/**
* combineURL
* 拼接url
* @param string $baseURL 基于的url
* @param array $keysArr 参数列表数组
* @return string 返回拼接的url
*/
public function combineURL($baseURL,$keysArr){
$combined = $baseURL."?";
$valueArr = array();
foreach($keysArr as $key => $val){
$valueArr[] = "$key=$val";
}
$keyStr = implode("&",$valueArr);
$combined .= ($keyStr);
return $combined;
}
/**
* get_contents
* 服务器通过get请求获得内容
* @param string $url 请求的url,拼接后的
* @return string 请求返回的内容
*/
public function get_contents($url){
if (ini_get("allow_url_fopen") == "1") {
//2015-3-5 wuxiao 尝试解决Maximum execution time of 30 seconds exceeded
//$response = file_get_contents($url);
$response = file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => "GET",
'timeout' => 10,
)
)));
}else{
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
//2015-3-5 wuxiao 尝试解决Maximum execution time of 30 seconds exceeded
curl_setopt ( $ci, CURLOPT_CONNECTTIMEOUT, 3 );
curl_setopt ( $ci, CURLOPT_TIMEOUT, 7 );
$response = curl_exec($ch);
curl_close($ch);
}
//-------请求为空
if(empty($response)){
$this->error->showError("50001");
}
return $response;
}
/**
* get
* get方式请求资源
* @param string $url 基于的baseUrl
* @param array $keysArr 参数列表数组
* @return string 返回的资源内容
*/
public function get($url, $keysArr){
$combined = $this->combineURL($url, $keysArr);
return $this->get_contents($combined);
}
/**
* post
* post方式请求资源
* @param string $url 基于的baseUrl
* @param array $keysArr 请求的参数列表
* @param int $flag 标志位
* @return string 返回的资源内容
*/
public function post($url, $keysArr, $flag = 0){
$ch = curl_init();
if(! $flag) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $keysArr);
curl_setopt($ch, CURLOPT_URL, $url);
//2015-3-5 wuxiao 尝试解决Maximum execution time of 30 seconds exceeded
curl_setopt ( $ci, CURLOPT_CONNECTTIMEOUT, 3 );
curl_setopt ( $ci, CURLOPT_TIMEOUT, 7 );
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
}
... ...
<?php
namespace Plugin\Partner\Sinaweibo;
use Plugin\Partner\Factory;
require dirname(__FILE__) . '/class/Saev2.class.php';
/**
* 新浪微博的调用接口
*
* @name Call
* @package lib/partner/sinaweibo
* @copyright yoho.inc
* @version 4.0 (2013-12-19 11:45:51)
* @author fei.hong <fei.hong@yoho.cn>
*/
class Call extends Factory
{
/*OAuth2.0对象*/
protected $oauth;
/*客户端操作对象*/
protected $client;
/**
* 初始化
*/
protected function init()
{
$this->oauth = new \SaeTOAuthV2($this->apiConfig['appId'], $this->apiConfig['appKey']);
}
/**
* 获取授权URL
*/
public function getAuthorizeUrl()
{
return $this->oauth->getAuthorizeURL($this->apiConfig['appCallbackUrl']);
}
/**
* 获取授权的TOKEN
*/
public function getAccessToken()
{
$token = array();
if (isset($_REQUEST['code']))
{
$keys = array();
$keys['code'] = $_REQUEST['code'];
$keys['redirect_uri'] = $this->apiConfig['appCallbackUrl'];
try
{
$token = $this->oauth->getAccessToken('code', $keys);
}
catch (Exception $e)
{
// do nothing
}
}
return $token;
}
/**
* 获取当前用户的基本资料
*
* @param array $token 授权成功的TOKEN, 默认为NULL
* @return array
*/
public function getUserInfo($token)
{
$userInfo = array();
if (is_array($token) && isset($token['uid']))
{
$this->client = new SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$userInfo = $this->client->show_user_by_id($token['uid']);
if (isset($userInfo['error_code']) && $userInfo['error_code'] > 0)
{
$userInfo = array();
}
}
return $userInfo;
}
/**
* 获取当前用户的关注列表
*
* @see http://open.weibo.com/wiki/2/friendships/friends
*
* @param string $token 已授权过的访问TOKEN
* @param array $params 参数列表,如下:
* @param integer $uid (要获取的用户的ID)
* @param integer count (单页返回的记录条数,默认为50,最大不超过200。)
* @param integer cursor (返回结果的游标,下一页用返回值里的next_cursor,上一页用previous_cursor,默认为0。
* @return array
*/
public function getFriends($token, $params)
{
$result = array();
if (is_array($token) && isset($token['access_token']))
{
$this->client = new SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$result = $this->client->friends_by_id($params['uid'], $params['cursor'], $params['count']);
if (isset($result['error_code']) && $result['error_code'] > 0)
{
$result = array();
}
}
return $result;
}
/**
* 获取用户的双向关注列表,即互粉列表
*
* @param type $token 授权成功的TOKEN
* @param type $params 参数列表
*/
public function getBilateral($token, $params)
{
$result = array();
if (is_array($token) && isset($token['access_token']))
{
$this->client = new SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$result = $this->client->bilateral($params['uid'], $params['page'], $params['count']);
if (isset($result['error_code']) && $result['error_code'] > 0)
{
$result = array();
}
}
return $result;
}
/**
* 同步分享
*
* @param array $token 授权成功的TOKEN
* @param string $content 要更新的微博信息。信息内容不超过140个汉字, 为空返回400错误。
* @param string $image 要发布的图片路径, 支持url。[只支持png/jpg/gif三种格式, 增加格式请修改get_image_mime方法]
* @param string $link URL地址, 通过该地址链接回来
* @return boolean false:失败, true:成功
*/
public function syncShare($token, $content, $image, $link)
{
$result = false;
if (is_array($token) && isset($token['access_token']))
{
$content .= $link;
$this->client = new SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$response = $this->client->upload($content, $image);
if (!isset($response['error_code']) || $response['error_code'] == 0)
{
$result = true;
}
}
return $result;
}
/**
* 加关注
*
* @param array $token 访问令牌
* @param integer $uid 需要关注的用户ID
* @param string $screenName 需要关注的用户昵称
* @return array
*/
public function follow($token, $uid = null, $screenName = null)
{
$result = array();
if (is_array($token) && isset($token['access_token']))
{
$this->client = new SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
if ($uid !== null)
{
$result = $this->client->follow_by_id($uid);
}
elseif ($screenName !== null)
{
$result = $this->client->follow_by_name($screenName);
}
}
return $result;
}
/**
* 发布文字微博
*
* @param array $token 访问令牌
* @param string $content 要发布的微博文本内容,必须做URLencode,内容不超过140个汉字
* @return array
*/
public function publish($token, $content)
{
$result = array();
if (is_array($token) && isset($token['access_token']) && is_string($content))
{
$this->client = new SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$this->client->update($content);
}
return $result;
}
/**
* 发送一条私信
*
* @param integer $uid 用户UID
* @param string $text 要发生的消息内容,文本大小必须小于300个汉字
* @param integer $id 需要发送的微博ID
* @return void
*/
public function sendMessage($token, $uid, $content, $id = null)
{
if (is_array($token) && isset($token['access_token']) && isset($uid))
{
$this->client = new SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$this->client->send_dm_by_id($uid, $content, $id);
}
}
}
\ No newline at end of file
... ...
<?php
defined('SITE_MAIN') || define('SITE_MAIN', 'http://www.yoho.cn');
return array(
'appId' => '2707954749',
'appKey' => '431730e25a8a0983964a740731c3cb7d',
'appCallbackUrl' => SITE_MAIN . '/passport/sso/partnercallback/partner/sinaweibo',
);
\ No newline at end of file
... ...
This diff could not be displayed because it is too large.
<?php
use Action\AbstractAction;
use LibModels\Wap\Home\IndexData as Index;
use LibModels\Wap\Home\IndexData;
/**
* 频道选择
... ... @@ -9,12 +9,12 @@ class IndexController extends AbstractAction
{
/**
* 启动首页
* 启动首页频道选择
*/
public function indexAction()
{
// 启动滚动图
$startBannerData = Index::getBannerStart();
$startBannerData = IndexData::getBannerStart();
$startBanner = array();
if($startBannerData['code'] == 200)
{
... ... @@ -25,9 +25,9 @@ class IndexController extends AbstractAction
}
// 启动频道数据
$homeChannels = Index::getHomeChannels();
$homeChannels = IndexData::getHomeChannels();
// 用户个人信息
$userProfile = Index::getUserProfile(0);
$userProfile = IndexData::getUserProfile(0);
/*echo '<pre>';
var_dump($homeChannels);exit;*/
... ...
<?php
use Action\AbstractAction;
use LibModels\Wap\Category\BrandData;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
/**
* 品牌
*/
class BrandController extends AbstractAction
{
public function indexAction()
{
// 获取品牌数据
$brandTopData = BrandData::getBrandTopData();
$brandsData = BrandData::getBrandsData();
$brandTop = array();
if($brandTopData['code'] == 200)
{
$brandTop = $brandTopData['data'];
}
$brands = array();
if($brandsData['code'] == 200)
{
$brands = $brandsData['data'];
}
echo '<pre>';
var_dump($brandTop, $brands);exit;
$this->_view->assign('title', 'YOHO!有货');
$this->_view->display('brand', compact('brands'));
}
}
\ No newline at end of file
... ...
<?php
use Action\AbstractAction;
use LibModels\Wap\Category\ClassData;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
/**
* 品牌
*/
class ClassController extends AbstractAction
{
public function indexAction()
{
$brandsData = ClassData::getClassesData();
$classes = array();
if($brandsData['code'] == 200)
{
$classes = $brandsData['data'];
}
echo '<pre>';
var_dump($classes);exit;
$this->_view->assign('title', 'YOHO!有货');
$this->_view->display('class', compact('classes'));
}
}
\ No newline at end of file
... ...
<?php
use Action\AbstractAction;
use LibModels\Wap\Category\FocusData;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
/**
* 品牌
*/
class FocusController extends AbstractAction
{
public function indexAction()
{
// 获取关注数据
$gender = $this->get('gender', '1,3');
$focusData = FocusData::getFocusData(0, $gender);
$focus = array();
if($focusData['code'] == 200)
{
$focus = $focusData['data'];
}
echo '<pre>';
var_dump($focus);exit;
$this->_view->assign('title', 'YOHO!有货');
$this->_view->display('class', compact('focus'));
}
}
\ No newline at end of file
... ...
<?php
use Action\AbstractAction;
use Plugin\Partner\Factory;
class LoginController extends AbstractAction
{
... ... @@ -40,4 +42,37 @@ class LoginController extends AbstractAction
$this->_view->assign('title', '国际账号登录');
$this->_view->display('interational', $data);
}
/**
* 支付宝账号登录:授权页面
*/
public function alipayAction()
{
Factory::create('alipay')->getAuthorizeUrl();
exit();
}
/**
* QQ账号登录:授权页面
*/
public function qqAction()
{
Factory::create('qqconnect')->getAuthorizeUrl();
exit();
}
/**
* 新浪微博账号登录:授权页面
*/
public function sinaAction()
{
header('Location:' . Factory::create('sinaweibo')->getAuthorizeUrl());
exit();
}
}
\ No newline at end of file
... ...