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

前置条件

  • 获取appId java

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

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

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

服务端

  • 在项目中的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, // 要缓存的数据
    });
  },
});
复制代码
  • 测试结果以下 : 后端

  • 下次再次进入不会弹框受权,若有须要,将用户受权信息删除掉便可,以下: api

以上就是支付宝小程序受权的部分,若是错误,请在评论区指出,蟹蟹你们的观看!

相关文章
相关标签/搜索