com.healthy.common.security.social.weixin.connet.WeixinOAuth2ConnectionFactory Maven / Gradle / Ivy
package com.healthy.common.security.social.weixin.connet;
import com.healthy.common.security.social.weixin.api.Weixin;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.support.OAuth2Connection;
import org.springframework.social.connect.support.OAuth2ConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2ServiceProvider;
/**
* 微信连接工厂
*/
public class WeixinOAuth2ConnectionFactory extends OAuth2ConnectionFactory {
/**
* @param appId
* @param appSecret
*/
public WeixinOAuth2ConnectionFactory(String providerId, String appId, String appSecret) {
super(providerId, new WeixinOAuth2ServiceProvider(appId, appSecret), new WeixinApiAdapter());
}
/**
* 由于微信的openId是和accessToken一起返回的,所以在这里直接根据accessToken设置providerUserId即可,不用像QQ那样通过QQAdapter来获取
*/
@Override
protected String extractProviderUserId(AccessGrant accessGrant) {
if (accessGrant instanceof WeixinAccessGrant) {
return ((WeixinAccessGrant) accessGrant).getOpenId();
}
return null;
}
@Override
public Connection createConnection(AccessGrant accessGrant) {
return new OAuth2Connection(getProviderId(), extractProviderUserId(accessGrant), accessGrant.getAccessToken(),
accessGrant.getRefreshToken(), accessGrant.getExpireTime(), getOAuth2ServiceProvider(), getApiAdapter(extractProviderUserId(accessGrant)));
}
@Override
public Connection createConnection(ConnectionData data) {
return new OAuth2Connection(data, getOAuth2ServiceProvider(), getApiAdapter(data.getProviderUserId()));
}
private ApiAdapter getApiAdapter(String providerUserId) {
return new WeixinApiAdapter(providerUserId);
}
private OAuth2ServiceProvider getOAuth2ServiceProvider() {
return (OAuth2ServiceProvider) getServiceProvider();
}
}