IDEA基于支付宝小程序之授权篇

前置条件

  • 获取appId

  • 添加获取会员信息功能列表
    步骤 :开发管理 -> 功能列表 -> 添加功能 -> 勾选会员信息 ->确认,效果如图:

    • 注意 :如果想获取手机号与姓名等真实信息,需要额外申请敏感信息流程
  • 设置密钥

    • 使用阿里的密钥生成工具生成私密钥。
    • 上传应用公钥生成支付宝公钥
      • 登录开放者平台 -- 查看选择自己的小程序 -- 设置 -- 开发设置 -- 接口加签方式 -- 设置应用公钥 -- 设置应用公钥 -- 把加签工具里的"公钥"内容复制粘贴进去,点击保存。效果查看:
      • 公钥用于签证使用

服务端

  • 在项目中的pom文件中加入以下依赖:
  • 在application.yml中添加appId,公钥,私钥的配置。
  • 注意 :公钥不是工具里的公钥内容,而是通过公钥生成的支付宝公钥内容
  • 添加读取配置文件java工具类 AliXcxProperty.java
@Data
@Component
@ConfigurationProperties(prefix = "alipaytest.ali.xcx")
public class AliXcxProperty {
    private String serverUrl;
    private String appId;
    private String privateKey;
    private String publicKey;
}
复制代码
  • AliAuthController.java
@Controller
public class AliAuthController {

    @Autowired
    private AliAuthService aliAuthService;

    @GetMapping("/auth")
    @ResponseBody
    public AlipayUserInfoShareResponse auth(@RequestParam(value="authCode") String authCode){
        System.out.println(authCode);
        AlipayUserInfoShareResponse auth = aliAuthService.auth(authCode);
        return auth;
    }
}
复制代码
  • AliAuthService.java
@Slf4j
@Service
public class AliAuthService {

    @Resource
    private AliXcxProperty aliXcxProperty;

    public AlipayUserInfoShareResponse auth(String authcode) {
        AlipayClient alipayClient = new DefaultAlipayClient(aliXcxProperty.getServerUrl(),
                aliXcxProperty.getAppId(),
                aliXcxProperty.getPrivateKey(),
                "JSON", "utf-8", aliXcxProperty.getPublicKey(), "RSA2");
        //获取uid&token
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");//值为authorization_code时,代表用code换取;值为refresh_token时,代表用refresh_token换取
        request.setCode(authcode);
        try {
                AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                log.info("auth success [{}]", JSONObject.toJSONString(response));

                AlipayUserInfoShareRequest alipayUserInfoShareRequest = new AlipayUserInfoShareRequest();
                AlipayUserInfoShareResponse alipayUserInfoShareResponse = alipayClient.execute(alipayUserInfoShareRequest, response.getAccessToken());
                if (alipayUserInfoShareResponse.isSuccess()) {
                    log.info("AlipayUserInfoShareResponse success [{}]", JSONObject.toJSONString(alipayUserInfoShareResponse));
                } else {
                    log.info("AlipayUserInfoShareResponse fail [{}]", JSONObject.toJSONString(alipayUserInfoShareResponse));
                }
                return alipayUserInfoShareResponse;
            } else {
                log.info("auth fail [{}]", JSONObject.toJSONString(response));
            }
        } catch (AlipayApiException e) {
            log.error("auth exception", e);
        }
        return null;
    }
} 
复制代码
  • 服务端授权代码完毕,发布即可

客户端

  • info.axml
  • info.js
const app = getApp();
Page({
  data: {
    userInfo:{}, //存放用户信息
    userLogin:false, //判断当前是否登录
    userNotLogin:true //判断当前是否登录
  },
  onLoad() {
    var me = this;
    var userInfo = app.getGlobalUserInfo(); //在全局缓存中获取用户信息
    if(userInfo!=null&&userInfo!=undefined){ //有则不发起授权登录
      me.setData({
        userInfo:userInfo,
        userLogin:true,
        userNotLogin:false
      })
      return;
    }
    //无缓存则发起授权登录,第一步先通过小程序api获取授权码authCode
    my.getAuthCode({
      scopes:"auth_user",
      success: (res) => {
        if(res!=null&&res!=undefined){
          console.log(res.authCode);
          //第一步成功则调用后端接口,并传入authCode
          my.request({
            url:app.myServerUrl+"/auth?authCode="+res.authCode,
            success(res){
              console.log(res.data);
              //成功则赋值到data数据域
              me.setData({
                userInfo : res.data,
                userLogin:true,
                userNotLogin:false,
              })
              //存入到缓存中
              app.setGlobalUserInfo(res.data);
            },
          })
        }
      },
    });
  },
  login(){
    this.onLoad();
  },
});
复制代码
  • app.js
App({
  myServerUrl:"https://app2134991587test.mapp-test.xyz", //线上云服务端的地址
  localhostServerUrl:"http://127.0.0.1:8080", //本地springboot开启内嵌的tomcat的地址,用于本地测试。
  //从本地缓存中获取全局的用户对象
  getGlobalUserInfo(){
    var golbalUserInfo = my.getStorageSync({
      key: 'globalUserInfo', // 缓存数据的key
    }).data;
    return golbalUserInfo;
  },
  setGlobalUserInfo(golbalUserInfo){
    my.setStorageSync({
      key: 'globalUserInfo', // 缓存数据的key
      data: golbalUserInfo, // 要缓存的数据
    });
  },
});
复制代码
  • 测试结果如下 :

  • 下次再次进入不会弹框授权,如有需要,将用户授权信息删除掉即可,如下:

以上就是支付宝小程序授权的部分,如果错误,请在评论区指出,蟹蟹大家的观看!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值