JAVA支付宝小程序授权登陆,并生成二维码(证书方式)

  • 接入准备
    https://opendocs.alipay.com/open/284/106001?ref=api
    根据文档进行创建小程序、配置相关信息(接口加签方式选择证书)
    生成二维码文档https://opendocs.alipay.com/mini/02owto

  • 开发接口

     1.添加依赖
    
		<!-- 支付宝核心sdk -->
        <dependency>
            <groupId>com.alipay.sdk</groupId>
            <artifactId>alipay-sdk-java</artifactId>
            <version>4.22.113.ALL</version>
        </dependency>

        <!-- 加解密钥sdk -->
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.62</version>
        </dependency>
2.配置信息
package com.ruoyi.common.utils.alipay;

public class AlipayConfig {

	/**
	 * 支付宝AppId
	 */
	public static final String APP_ID = "";

	// 商户id
	public static String SELLERID = "";

	// 应用私钥 pkcs8格式的
	public static String RSA_PRIVATE_KEY = "";

	// 支付宝公钥
	public static String ALIPAY_PUBLIC_KEY = "";
	
	// 请求网关地址
	public static String URL = "https://openapi.alipay.com/gateway.do";
	
	// 编码
	public static String CHARSET = "UTF-8";
	// 返回格式
	public static String FORMAT = "json";
	// 日志记录目录
	public static String log_path = "/log";
	// RSA2
	public static String SIGNTYPE = "RSA2";
}
3.工具类AlipayUtils
package com.ruoyi.common.utils.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayOpenAppQrcodeCreateModel;
import com.alipay.api.request.AlipayOpenAppQrcodeCreateRequest;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipayOpenAppQrcodeCreateResponse;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;

public class AlipayUtils {

	/**
	 * 服务端获取access_token、user_id
	 * 
	 * @param authCode
	 * @return
	 * @throws Exception
	 */
	public static AlipaySystemOauthTokenResponse getAccessToken(String authCode) throws Exception {
		CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
		// 实例化客户端(参数:网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型)
		certAlipayRequest.setServerUrl(AlipayConfig.URL);
		certAlipayRequest.setAppId(AlipayConfig.APP_ID);
		certAlipayRequest.setPrivateKey(AlipayConfig.RSA_PRIVATE_KEY);
		certAlipayRequest.setFormat(AlipayConfig.FORMAT); // JSON
		certAlipayRequest.setCharset(AlipayConfig.CHARSET); // UTF-8
		certAlipayRequest.setSignType(AlipayConfig.SIGNTYPE); // RSA2
		// 上传csr文件后 完成配置,支付宝后台能下载3个文件
		// 应用公匙/home/ruoyi
		certAlipayRequest.setCertPath("");
		// 支付宝公匙
		certAlipayRequest.setAlipayPublicCertPath("/home/ruoyi/xmcrt/alipayCertPublicKey_RSA2.crt");
		// 支付宝 根 公匙
		certAlipayRequest.setRootCertPath("/home/ruoyi/xmcrt/alipayRootCert.crt");

		DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.system.oauth.token
		AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
		request.setGrantType("authorization_code");
		request.setCode(authCode);
		AlipaySystemOauthTokenResponse response = alipayClient.certificateExecute(request);

		if (response.isSuccess()) {
			System.out.println("调用成功");
		} else {
			System.out.println("调用失败");
		}
		return response;
	}

	/**
	 * 生成支付宝小程序二维码
	 * 
	 * @param urlParam   小程序中能访问到的页面路径
	 * @param queryParam 小程序的启动参数,打开小程序的query ,在小程序 onLaunch的方法中获取
	 * @param describe   对应的二维码描述
	 * @return
	 */
	public static String createQrCode(String urlParam, String queryParam, String describe) {
		String qrCodeUrl = "";
		try {
			CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
			// 实例化客户端(参数:网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型),为了取得预付订单信息
			certAlipayRequest.setServerUrl(AlipayConfig.URL);
			certAlipayRequest.setAppId(AlipayConfig.APP_ID);
			certAlipayRequest.setPrivateKey(AlipayConfig.RSA_PRIVATE_KEY);
			certAlipayRequest.setFormat(AlipayConfig.FORMAT);
			certAlipayRequest.setCharset(AlipayConfig.CHARSET);
			certAlipayRequest.setSignType(AlipayConfig.SIGNTYPE);
			// 上传csr文件后 完成配置,支付宝后台能下载3个文件
			// 应用公匙/home/ruoyi
			certAlipayRequest.setCertPath("");
			// 支付宝公匙
			certAlipayRequest.setAlipayPublicCertPath("/home/ruoyi/xmcrt/alipayCertPublicKey_RSA2.crt");
			// 支付宝 根 公匙
			certAlipayRequest.setRootCertPath("/home/ruoyi/xmcrt/alipayRootCert.crt");

			DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

			// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.open.app.qrcode.create
			AlipayOpenAppQrcodeCreateRequest request = new AlipayOpenAppQrcodeCreateRequest();

			// SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式
			AlipayOpenAppQrcodeCreateModel model = new AlipayOpenAppQrcodeCreateModel();
			model.setUrlParam(urlParam);
			model.setQueryParam(queryParam);
			model.setDescribe(describe);
			request.setBizModel(model);
			AlipayOpenAppQrcodeCreateResponse response = alipayClient.certificateExecute(request);
			System.out.println(response.getQrCodeUrl());
			qrCodeUrl = response.getQrCodeUrl();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return qrCodeUrl;
	}
}
4.controller层接口
@PostMapping("/authLogin")
	@ResponseBody
	public AjaxResult authLogin(@RequestParam String authCode, @RequestParam String nickName,
			@RequestParam String avatar) {
		logger.info("-----------授权登录 authCode[{}], nickName[{}], avatar[{}], parentId[{}]", authCode, nickName, avatar,
				parentId);
		try {
			// 1. 服务端获取access_token、user_id
			AlipaySystemOauthTokenResponse response = AlipayUtils.getAccessToken(authCode);
			if (response.isSuccess()) {
				// 获取用户信息
				String accessToken = response.getAccessToken();
				String alipayUserId = response.getUserId();
				logger.info("-----------accessToken:" + accessToken);
				logger.info("-----------alipayUserId:" + alipayUserId);

				XmUser xmUser = iXmUserService.getByAlipayUserId(alipayUserId);
				if (xmUser != null) {
					return AjaxResult.success(xmUser);
				} else {
					XmUser newXmUser = new XmUser();
					newXmUser.setAlipayUserId(alipayUserId);
					newXmUser.setNickName(nickName);
					newXmUser.setAvatar(avatar);
					iXmUserService.insertXmUser(newXmUser);
					// 生成用户id二维码
					String qrCodeUrl = AlipayUtils.createQrCode("pages/index/index",newXmUser.getId(), "二维码");
					XmUser newXmUser2 = new XmUser();
					newXmUser2.setId(newXmUser.getId());
					newXmUser2.setQrCode(qrCodeUrl);
					iXmUserService.updateXmUser(newXmUser2);
					return AjaxResult.success(iXmUserService.getByAlipayUserId(alipayUserId));
				}
			}
			return AjaxResult.error("获取access_token - 调用失败!");
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("授权登录异常");
		}
	}
注意:将证书文件放在服务器后建议重启一下tomcat

你可能感兴趣的:(java,小程序)