자바 가 알 리 페 이에 접속 하여 제3자 에 게 로그 인 권한 을 부여 하 는 전체 절차

개발 전 준비
알 리 페 이 개발 플랫폼 .
알 리 페 이 모래 상자 환경 신청 사용


!!!중점 권한 수여 리 셋 주 소 는 모든 경 로 를 써 야 합 니 다.즉,controller 최종 경로 입 니 다.(아래 에 구체 적 인 세부 사항 이 있 습 니 다)
RSA 2 키 생 성:알 리 페 이 생 성 키 주소 제공
사용자 권한 획득
알 리 페 이 권한 부여 연결 생 성
appid+리 셋 경 로 를 사용 하여 경 로 를 리 셋 합 니 다=위 에 설 정 된 전체 경로 의 구체 적 인 경로:

https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?
app_id=2016####&scope=auth_user&edirect_uri=http://ip |    +     
사용자 정의 매개 변수의 연결 도 사용 할 수 있 습 니 다:

https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2016####
&state=     (       )&scope=auth_user&edirect_uri=http://ip |    +     
구체 적 으로 어떻게 사용 합 니까?온라인 QR 코드 생 성 용 알 리 페 이 샌 드 박스 app 스 캔
리 셋 주소 수신 알 리 페 이 파라미터
구축 요청 알 리 페 이 클 라 이언 트
yml:

#      
ali:
  appId: 2016####

  #      
  merchantPrivateKey:        
  #      
  alipayPublicKey:                      
  #     
  signType: RSA2
  #       
  charset: UTF-8
  #       
  format: json
  #       https://openapi.alipay.com/gateway.do     
  gatewayUrl: https://openapidev.alipay.com/gateway.do #dev   

Property:

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 *      
 */
@Data
@Component
@ConfigurationProperties(prefix = "ali")
public class AliPayProperty {

    /**
     *    APPID
     */
    public String appId;
    /**
     *     ,  PKCS8  RSA2  
     */
    public String merchantPrivateKey ;
    /**
     *      ,    :https://openhome.alipay.com   APPID       。
     */
    public String alipayPublicKey;
    /**
     *       
     */
    public String format;
    /**
     *     
     */
    public String signType;
    /**
     *       
     */
    public String charset;
    /**
     *        https://openapi.alipay.com/gateway.do       
     */
    public String gatewayUrl;

    /**
     *       
     * @return
     */
    public AlipayClient getAlipayClient(){
        AlipayClient alipayClient = new DefaultAlipayClient(
                this.gatewayUrl,
                this.appId,
                this.merchantPrivateKey,
                this.format,
                this.charset,
                this.alipayPublicKey,
                this.signType);
        return alipayClient;
    }

}
비 즈 니스 프로 세 스 코드
controller:

@GetMapping(value = "/loginCallBack")
public String loginCallBack(HttpServletRequest request){
	return aliPayService.loginCallBack(request);
}
service:

public String loginCallBack(HttpServletRequest request){
	//           
	Map<String,String> map = this.getAliPayParam(request);
	//        code
	String code = map.get("auth_code");
	//       
    AlipayClient alipayClient = aliPayProperty.getAlipayClient();
	//      token
    AlipaySystemOauthTokenResponse aliUserToken = 
    			this.getAliUserToken(code, alipayClient,0);
    //      
    AlipayUserInfoShareResponse infoShareResponse = 
    			this.getUserInfo(alipayClient, aliUserToken, 0);
    //!!!                             
    return "SUECCSS";
}
패키지 수신 매개 변수 방법:

    public Map<String,String> getAliPayParam(HttpServletRequest request) {
        Map<String,String> map = new HashMap();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //     ,            
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            map.put(name, valueStr);
            log.info("         :{}",map);
        }
        return map;
    }
token 가 져 오 는 방법:

    private AlipaySystemOauthTokenResponse getAliUserToken(String code, AlipayClient alipayClient,int number) throws AlipayApiException {
        AlipaySystemOauthTokenRequest alipaySystemOauthTokenRequest = new AlipaySystemOauthTokenRequest();
        alipaySystemOauthTokenRequest.setGrantType("authorization_code");
        alipaySystemOauthTokenRequest.setCode(code);
        AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(alipaySystemOauthTokenRequest);
        log.info("    +++++++++++++++token:{}+++++++++++++++",oauthTokenResponse.getAccessToken());
        log.info("    +++++++++++++++uuid:{}+++++++++++++++",oauthTokenResponse.getUserId());
        if(oauthTokenResponse.isSuccess()){
            log.info("  ");
        } else {
        	log.info("***********  ,     :{} ",number);
            number += 1;
            if(number < 3){
                log.info("  token  ,  :*******{}*******",number);
                return this.getAliUserToken(apiPayLoginReq, alipayClient, number);
            }
        }
        return oauthTokenResponse;
    }
사용자 알 리 페 이 정보 획득 방법:

private AlipayUserInfoShareResponse getUserInfo(AlipayClient alipayClient,AlipaySystemOauthTokenResponse aliUserToken,int number) throws AlipayApiException {
        AlipayUserInfoShareRequest alipayUserInfoShareRequest = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse infoShareResponse = alipayClient.execute(alipayUserInfoShareRequest,aliUserToken.getAccessToken());
        log.info("----------------         :{}",infoShareResponse.getBody());
        UserInfoReq userInfoReq = new UserInfoReq();
        if(infoShareResponse.isSuccess()){
            //      
            log.info("----------------            :{}",userInfoReq);
            log.info("  ");
        } else {
            log.info("***********  ,     :{} ",number);
            number += 1;
            if(number < 3){
                log.info("        ,  :*******{}*******",number);
                return this.getUserInfo(alipayClient,aliUserToken,number);
            }
            return infoShareResponse ;
        }
    }
직렬 업무
사용자 가 코드 를 스 캔 한 후 설정 한 리 셋 주소 로 이동 합 니 다!!그러나 코드 에서 되 돌아 오 는 것 은 success 이기 때문에 사용자 가 받 은 것 은 문자열 일 뿐 입 니 다.따라서 이 곳 은 알 리 페 이 를 설정 하여 전단 주 소 를 되 돌려 주 고 파 라 메 터 를 백 엔 드 백 엔 드 에 그대로 전달 하여 분석 에 성공 한 후 전단 에서 사용자 에 게 다음 작업 을 유도 합 니 다.
총결산
자바 가 알 리 페 이에 접속 하여 제3자 에 게 로그 인 권한 을 부여 하 는 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 자바 가 알 리 페 이에 접속 하 는 권한 수여 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 저 희 를 많이 사랑 해 주세요!

좋은 웹페이지 즐겨찾기