授權訪問官方文檔
獲取會員信息官方文檔
下載支付寶sdk後解壓放到extend目錄下
在public/index.php中定義常量
參考文檔
define('ALI_PATH',__DIR__.'/../extend/alipay/aop/');
創建控制器並寫入代碼
require ALI_PATH.'AopClient.php';
require ALI_PATH.'request/AlipaySystemOauthTokenRequest.php';
require ALI_PATH.'request/AlipayUserInfoShareRequest.php';
class Ali extends Controller{
public static $appid = ''; //appid
public static $pub_key = '';//應用公鑰
public static $prikey = ''; //應用私鑰
public static $alipubkey = '';//支付寶公鑰
public function alilogin()
{
/**
* 該方法執行後支付寶會調用你自己定義的回調
*/
$appid = self::$appid;
$state = md5(uniqid(rand(), TRUE));
$nurl = ''; //回調地址
$url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.$appid.'&scope=auth_user&redirect_uri='.$nurl.'&state='.$state;
echo("<script> top.location.href='" . $url . "'</script>");
}
//回調代碼
public function login()
{
//獲取授權token
$authcode = input('auth_code');
$aop = new \AopClient ();
$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
$aop->appId = self::$appid;
$aop->rsaPrivateKey = self::$prikey;
$aop->alipayrsaPublicKey=self::$alipubkey;
$aop->apiVersion = '1.0';
$aop->signType = 'RSA2';
$aop->postCharset='utf-8';
$aop->format='json';
$request = new \AlipaySystemOauthTokenRequest ();
$request->setGrantType("authorization_code");
$request->setCode($authcode);
$result = $aop->execute ( $request);
// var_dump($result->alipay_system_oauth_token_response);die;
if(isset($result->alipay_system_oauth_token_response->access_token))
{
//獲取會員信息
$requests = new \AlipayUserInfoShareRequest ();
$results = $aop->execute ( $requests , $result->alipay_system_oauth_token_response->access_token );
if($results->alipay_user_info_share_response->code == 10000)
{
$data = AliUsers::where('ali_user_id',$result->alipay_system_oauth_token_response->user_id)->find();
if(!count($data))
{
$data = new AliUsers();
$data->ali_user_id = $result->alipay_system_oauth_token_response->user_id;
$data->ctime = time();
$data->save();
}
$data->access_token = $result->alipay_system_oauth_token_response->access_token;
$data->avatar = $results->alipay_user_info_share_response->avatar;
$data->province = $results->alipay_user_info_share_response->province;
$data->city = $results->alipay_user_info_share_response->city;
$data->nick_name = $results->alipay_user_info_share_response->nick_name;
$data->gender = $results->alipay_user_info_share_response->gender;
$data->ltime = time();
$data->save();
session('is_login',true);
session('user_id',$result->alipay_system_oauth_token_response->user_id);
return $this->redirect(''); //登錄成功,跳轉到首頁
}else{
$this->error('登錄異常');
}
}else{
$this->error('登錄異常');
}
//object(stdClass)#43 (6) { ["access_token"]=> string(40) "authusrBfc3814381c2b49c096b672ffef3f7X67" ["alipay_user_id"]=> string(32) "20881040009279002140758050319167" ["expires_in"]=> int(1296000) ["re_expires_in"]=> int(2592000) ["refresh_token"]=> string(40) "authusrB2f29604ff780444dbb04b3303e571B67" ["user_id"]=> string(16) "2088512270592674" }
}
}