轉載自:https://blog.csdn.net/wang78699425/article/details/78666401
支付寶 APP登錄 獲取用戶信息 PHP(轉)
支付寶APP登錄服務端流程如下:
1、換取授權訪問令牌
2、查詢用戶信息
APP調用sdk組裝授權登錄請求(系統交互流程),成功后,支付寶會返回 auth_code,利用此 auth_code 請求 PHP,PHP接收到參數后,先利用 auth_code 獲取到 授權訪問令牌 access_token(接口文檔),再根據 access_token 來獲取用戶信息(接口文檔)。
具體代碼如下:
try { $code = trim($_POST['auth_code']); if (empty($code)) { throw new Exception('缺少參數', 0); } //獲取access_token $aop = new AopClient (); $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do'; $aop->appId = $alipay_config['app_id']; $aop->rsaPrivateKey = trim($alipay_config['application_private']); $aop->format = 'json'; $aop->charset = 'UTF-8'; $aop->signType = 'RSA2'; $aop->alipayrsaPublicKey = trim($alipay_config['alipay_public']); $aop->apiVersion = '1.0'; $request = new AlipaySystemOauthTokenRequest(); $request->setGrantType("authorization_code"); $request->setCode($code); $result = $aop->execute($request); $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response"; $resultData = (array) $result->$responseNode; if (empty($resultData['access_token'])) { throw new Exception('獲取access_token失敗', 0); } //獲取用戶信息 $request = new AlipayUserInfoShareRequest (); $result = $aop->execute ( $request , $resultData['access_token'] ); $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response"; $userData = (array) $result->$responseNode; if (empty($userData['code']) || $userData['code'] != 10000) { throw new Exception('獲取用戶信息失敗', 0); } /** * user_id 支付寶用戶的userId * avatar 用戶頭像地址 * province 省份名稱 * city 市名稱。 * nick_name 用戶昵稱 * is_student_certified 是否是學生 * user_type 用戶類型(1/2) 1代表公司賬戶2代表個人賬戶 * user_status 用戶狀態(Q/T/B/W)。 Q代表快速注冊用戶 T代表已認證用戶 B代表被凍結賬戶 W代表已注冊,未激活的賬戶 * is_certified 是否通過實名認證。T是通過 F是沒有實名認證。 * gender 性別(F:女性;M:男性)。 * */ //業務邏輯 echo json_encode(['code' => 1, 'msg' => '登錄成功']); exit; } catch (Exception $exception) { echo json_encode(['code' => $exception->getCode(), 'msg' => $exception->getMessage()]); exit; }