JAVA接入支付宝授权第三方登录

开发前准备

支付宝开发平台.
支付宝接口API.
支付宝接口Demo和接口介绍.

提供根据上面这两个文档再加上支付宝客服基本上开发没什么难度了,demo代码直接用,服务端这边只需要做好接口幂等、数据补偿就本上业务就完成了。

支付宝沙箱环境申请使用

在这里插入图片描述

在这里插入图片描述
!!!重点 授权回调地址必须要写全路径也就是controller最终路径(下面有具体细节)
RSA2的密钥生成: 支付宝提供生成密钥地址.

获取用户授权

生成唤起支付宝授权连接

用到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 | 域名 + 接口地址

具体怎么用??? 在线生成二维码用支付宝沙箱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是沙箱

在这里插入图片描述

maven

  <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
  </dependency>
  <dependency>
      <groupId>com.alipay.sdk</groupId>
      <artifactId>alipay-sdk-java</artifactId>
      <version>3.4.49.ALL</version>
  </dependency>

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,用户收到的只是个字符串。所以此处因该是配置支付宝去回调前端地址 然后参数让前端原封不动传向后端 后端解析成功后,前端引导用户进行下一步操作

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值