获取支付宝会员信息
获取支付宝会员信息
一、支付宝蚂蚁金服配置
1) 蚂蚁金服开发平台地址 , 进入系统支付宝扫码登录–开发者中心–网页&移动应用 ,看到如下页面,此时我的应用列表为空的,添加之后的应用将显示在此列表中。
2)根据需要选择创建应用,填写应用名
3)填写完应用名称创建应用,然后对应用进行编辑,上传应用图标,添加功能列表,根据需要添加相应的功能
4)开发设置需要填写授权回调地址,加签方式生成公钥和私钥,这些在获取会员信息时都需要使用的
二、项目配置
1)首先将需要的一些配置信息,写入配置文件中
2) 项目代码
UserAuthUtils.java代码
package com.wangshang.common.filter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Properties;
import org.slf4j.Logger;
import com.alibaba.common.lang.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.wangshang.common.PropertiesUtil;
import com.wangshang.common.Result;
import com.wangshang.common.log.LoggerProxy;
public class UserAuthUtils {
private static Logger logger = LoggerProxy.ProxyLogger("interceptor");
private static String APP_ID = null;
private static String ALIPAY_PUBLIC_KEY = null;
private static String PUBLIC_URL = null;
private static String USER_AUTH_LOGIN_URL = null;
private static AlipayClient alipayClient =null;
public static AlipayClient getAlipayClient() {
if(alipayClient==null) {
Properties properties = PropertiesUtil.getProperties("service.properties");
APP_ID = properties.getProperty("app_id");
ALIPAY_PUBLIC_KEY = properties.getProperty("alipay_public_key");
PUBLIC_URL = properties.getProperty("public_url");
USER_AUTH_LOGIN_URL = properties.getProperty("user_auth_login_url");
alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID,properties.getProperty("private_key"), "json", "UTF-8", properties.getProperty("alipay_public_key"),"RSA2");
}
return alipayClient;
}
/**
* 静默授权返回授权url
*
* @param redirectUri
* @return
* @throws AlipayApiException
* @throws IOException
*/
public static String getUserMobileAuthPageUrlSilent(String redirectUri) {
getAlipayClient();
String tiaozhuanUrl = USER_AUTH_LOGIN_URL + "?app_id=" + APP_ID + "&scope=auth_user&redirect_uri="
+ redirectUri;
try {
tiaozhuanUrl="https://auth.alipay.com/login/index.htm?goto="+URLEncoder.encode(tiaozhuanUrl,"utf-8");
} catch (UnsupportedEncodingException e) {
logger.info("url处理异常");
}
return tiaozhuanUrl;
}
/**
* 显性授权返回授权url
*
* @param redirectUri
* @return
* @throws AlipayApiException
* @throws IOException
*/
public static String getUserMobileAuthPageUrl(String redirectUri) {
getAlipayClient();
String tiaozhuanUrl = USER_AUTH_LOGIN_URL + "?app_id=" + APP_ID + "&scope=auth_user&redirect_uri="
+ redirectUri;
try {
tiaozhuanUrl="https://auth.alipay.com/login/index.htm?goto="+URLEncoder.encode(tiaozhuanUrl,"utf-8");
} catch (UnsupportedEncodingException e) {
logger.info("url处理异常");
}
return tiaozhuanUrl;
}
/**
* 通过 authCode获取 accessToken方法
*
* @param authCode
* @return
* @throws AlipayApiException
* @throws IOException
*/
public static Result<AlipaySystemOauthTokenResponse> getAccessTokenResponse(String authCode) {
Result<AlipaySystemOauthTokenResponse> result = new Result<AlipaySystemOauthTokenResponse>();
if (StringUtil.isBlank(authCode)) {
logger.info("getAccessTokenResponse occur error: authCode is null, authCode=" + authCode);
result.setMsg("authCode为空!");
return result;
}
try {
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setGrantType("authorization_code");
request.setCode(authCode);
logger.info("getAccessTokenResponse start call ,params: APP_ID = " + APP_ID);
logger.info("getAccessTokenResponse start call ,params: PUBLIC_URL = " + PUBLIC_URL);
logger.info("getAccessTokenResponse start call ,params: USER_AUTH_LOGIN_URL = " + USER_AUTH_LOGIN_URL);
logger.info("private -----------------------start-----------");
logger.info("getAccessTokenResponse start call ,params: ALIPAY_PUBLIC_KEY = " + ALIPAY_PUBLIC_KEY);
logger.info("public -----------------------end-----------");
AlipaySystemOauthTokenResponse response = getAlipayClient().execute(request);
if (response.isSuccess()) {
logger.info("getAccessTokenResponse 调用成功, ");
logger.info("getAccessTokenResponse params: authCode=" + authCode + ", response: "
+ JSONObject.toJSONString(response));
result.setSuccess(true);
result.setData(response);
} else {
logger.info("getAccessTokenResponse 调用失败");
logger.info("getAccessTokenResponse params: authCode=" + authCode + ", " + response.getSubCode() + ":"
+ response.getSubMsg());
result.setMsg(response.getSubMsg());
result.setData(response);
}
} catch (Exception e) {
logger.error("getAccessTokenResponse occur error: ", e);
logger.info("getAccessTokenResponse occur error: causemsg= " + e.getCause());
logger.info("getAccessTokenResponse occur error: causemsg= " + e.getMessage());
result.setMsg(e.getMessage());
}
return result;
}
/**
* 获取支付宝会员信息
*
* @param accessToken
* @return
*/
public static Result<AlipayUserInfoShareResponse> getUserInfo(String accessToken) {
Result<AlipayUserInfoShareResponse> result = new Result<AlipayUserInfoShareResponse>();
try {
AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse response = getAlipayClient().execute(request, accessToken);
if (response.isSuccess()) {
result.setSuccess(true);
result.setData(response);
} else {
logger.info("回调异常:"+JSONObject.toJSONString(response));
result.setData(null);
}
} catch (Exception ex) {
logger.error("获取支付宝会员信息", ex);
}
return result;
}
}
IndexController.java 获取支付宝用户信息回调地址代码
package com.wangshang.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.common.lang.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.wangshang.common.PropertiesUtil;
import com.wangshang.common.Result;
import com.wangshang.common.filter.Interceptor;
import com.wangshang.common.filter.UserAuthUtils;
import com.wangshang.common.log.LoggerProxy;
@Controller
public class IndexController {
private Logger logger=LoggerProxy.ProxyLogger(IndexController.class);
private static String LOGION_URL = PropertiesUtil.GetValueByKey("service.properties", "isoftweb_login_index");
@RequestMapping("auth/back")
public void authBack(HttpSession session,HttpServletRequest request,HttpServletResponse response) {
try {
String authcode = request.getParameter("auth_code");
Result<AlipaySystemOauthTokenResponse> tokenResult = UserAuthUtils.getAccessTokenResponse(authcode);
if (!tokenResult.isSuccess()) {
logger.info("LoginInterceptor#index 获取token和userId失败:" + tokenResult.getMsg());
request.setAttribute("errorMessage","通过authcode 获取 token失败, authcode = " + authcode + " 失败原因: " + tokenResult.getMsg());
}
String zfb_id = tokenResult.getData().getUserId();
logger.info("LoginInterceptor 获取userId成功!userId = " + zfb_id);
if(StringUtil.isNotBlank(zfb_id)) {
session.setAttribute("zfb_id", zfb_id);
String zfb_key = "zfb" + zfb_id;
Map<String,Boolean> existsMap=new HashMap<String,Boolean>();
existsMap.put("isAvatar",Boolean.FALSE);
Object[] data =_menuService.interceptor(zfb_id,existsMap);
if(data==null) {
session.setAttribute("rl","x");
Interceptor.out(response, "非法请求2", request, zfb_id);
return;
}
if(!existsMap.get("isAvatar")) {
Result<AlipayUserInfoShareResponse> result=UserAuthUtils.getUserInfo(tokenResult.getData().getAccessToken());
AlipayUserInfoShareResponse res=result.getData();
if(res.isSuccess()) {
_menuService.addUserImag(zfb_id,res.getNickName(),res.getAvatar());
}
}
jedis.del("zfb" + zfb_id);
jedis.add(zfb_key+"f0","1");
for(int index=0;index<data.length;index++) {
@SuppressWarnings("unchecked")
Map<String,Object> dataMap=(Map<String, Object>) data[index];
if(dataMap!=null) {
String funckey=zfb_key+"f"+dataMap.get("id");
if(dataMap.keySet().size()==1) {
jedis.add(funckey, "1");
}else {
for(String mapKey:dataMap.keySet()) {
if(mapKey.equals("id")) {
continue;
}
if(mapKey.equals("role_id")) {
jedis.add(funckey,String.valueOf(dataMap.get(mapKey)));
}else {
jedis.add(funckey+mapKey,JSONObject.toJSONString(dataMap.get(mapKey)));
}
}
}
}
}
}
response.sendRedirect("/wangshang-web/index?t="+System.currentTimeMillis());
response.setStatus(301);
}catch(Exception ex) {
logger.error("授权回调页面",ex);
}
}
}
根据UserAuthUtils和IndexController代码,从配置文件server.propertise中获取支付宝中的一些关键数据,即可获取会员信息。