AlipayCertHelper.java 13.3 KB
package com.yohoufo.user.helper;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayUserCertifyOpenCertifyRequest;
import com.alipay.api.request.AlipayUserCertifyOpenInitializeRequest;
import com.alipay.api.request.AlipayUserCertifyOpenQueryRequest;
import com.alipay.api.response.AlipayUserCertifyOpenCertifyResponse;
import com.alipay.api.response.AlipayUserCertifyOpenInitializeResponse;
import com.alipay.api.response.AlipayUserCertifyOpenQueryResponse;
import com.yoho.core.security.AlipayOpenapi;
import com.yoho.core.security.AlipayOpenapiHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;

/**
 * 支付宝刷脸实名认证
 *
 * 1. 身份认证初始化
 * 2. 执行身份认证能力
 * 3. 查询身份认证结果
 *
 * @ClassName AliCertificationHelper
 * @Author xinfei
 * @Date 2019/7/26
 * @Created add by xinfei/Kelvin 2019/7/26
 **/
public class AlipayCertHelper {

    private final static Logger logger = LoggerFactory.getLogger(AlipayCertHelper.class);

    /**
     * 支付宝应用APPID
     */
    private static String APP_ID =  "2016091401906455";


    /**
     * 支付宝应用APPID
     */
    private static String NEW_APP_ID =  "2021001108677633";

    /**
     * 支付宝请求地址
     */
    private static String ALI_URL="https://openapi.alipay.com/gateway.do";

    /**
     * 支付宝加密私钥
     */
    private static String APP_PRIVATE_KEY =
            "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCIUEvqn36aBznEQ0LaoM6Cjb8Mf4iNI+XZc41DUumEj0IQCEBXx60Nil5IKZRETiXcKxMV24T1k1Ep8LfulIuaa4DOgxZgm0LlmJi/S8QlJXjDdMATyU84anGcoT8TQbC9Tq9HEtkCMcYBJHIOJA4ZdLEhEH9gmoArsHI5K6ucaOjDRgmzgKxX1slg8kiYr8ysLq2nRUarwBuZ1k0B5hypALzwkiJoFKBgiJYAibIY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pA8dbBtFgu/au1a9fB0xIxiKgFZC6TAXWtUjf46CWks5UPqD3akwy5ZsWvhFRtugb/fBAq8fyrYA09hbClWh5YQlrHgJe90aU/a2vfQjQKBgQCWqyADlcPf/H+B/jyeajpevx8MFTwJU2bCJpwBq9xxOICBbozjSK2RJPCxbwrSUwvHZcPL9hRgCOF4o2vGP5t0ghNGdMJPUSVypUarL1B7ag76hjjhGQ1KzRy2sz0O74WrBdW2rP79FK3GkXSEaLF4UxtIQpnv1s3GQT6zm6F12g==";

    /**
     * 支付宝公钥
     */
    private static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3F+OpzvomabsyafmGUNrpMhFnBw/AJkJHDQa93vMSl5nk6mjje8/e39HfS/0Y7FQDu1bSA3jEgNpkDwjBpsa2fMMk+QdMb/I/fWQumibx8Mnc3/TjsSNPOP81Gkvz3yX8QRWHJIe+tMfZ51BoljKhSx5FQcHKQ2zq49IMuMi0IFzAgaPGOcvtT7Z3czrYtIpF3cAAj/PzflwfzXm3/5Krtuj71LdeRZeIKuYUXL7REP6/MoUJHvFjmLdWak7Uh+9PqX8lt8MZ0sOv21doMEkDhqrumDoSIPNB3/+nQQgpaekkogqcz5JnfTdJC8SEs79Enhgwisjt2Utb83b73qZQIDAQAB";

    /**
     * 请求编码
     */
    private final static String CHARSET = "utf-8";

    /**
     * 请求格式
     */
    private final static String FORMAT = "json";

    /**
     * 加密方式
     */
    private final static String SIGN_TYPE = "RSA2";//目前支持RSA2和RSA,推荐使用RSA2

    /**
     * 支付宝刷脸实名认证初始化
     *
     * @return
     */
    public static String alipayCertifyInit(String certName, String certNO) {
        AlipayClient alipayClient = new DefaultAlipayClient(ALI_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

        AlipayUserCertifyOpenInitializeRequest request = new AlipayUserCertifyOpenInitializeRequest();
        //构造身份信息json对象
        JSONObject identityObj = new JSONObject();
        //身份类型,必填,详细取值范围请参考接口文档说明
        identityObj.put("identity_type", "CERT_INFO");
        //证件类型,必填,详细取值范围请参考接口文档说明
        identityObj.put("cert_type", "IDENTITY_CARD");
        //真实姓名,必填
        identityObj.put("cert_name", certName);
        //证件号码,必填
        identityObj.put("cert_no", certNO);

        //构造商户配置json对象
        JSONObject merchantConfigObj = new JSONObject();
        // 设置回调地址,必填. 如果需要直接在支付宝APP里面打开回调地址使用alipay协议,参考下面的案例:appId用固定值 20000067,url替换为urlEncode后的业务回跳地址
        merchantConfigObj.put("return_url", "yohobuyufo://www.yohobuy.com/ufo");

        //构造身份认证初始化服务业务参数数据
        JSONObject bizContentObj = new JSONObject();
        //商户请求的唯一标识,推荐为uuid,必填
        bizContentObj.put("outer_order_no", UUID.randomUUID());
        bizContentObj.put("biz_code", "FACE");
        bizContentObj.put("identity_param", identityObj);
        bizContentObj.put("merchant_config", merchantConfigObj);
        request.setBizContent(bizContentObj.toString());

        //发起请求
        try {
            AlipayUserCertifyOpenInitializeResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                String certifyId = response.getCertifyId();
                logger.info("AlipayCertHelper.alipayCertifyInit: init result. certID is {}, certName is {}, certifyId is {}", certNO, certName, certifyId);
                return certifyId;
            }
        }catch (Exception e){
            logger.error("AlipayCertHelper.alipayCertifyInit: Alipay init failed. certID is {}, certName is {}", certNO, certName, e);
        }
        return null;
    }


    /**
     * 支付宝刷脸实名认证初始化
     *
     * @return
     */
    public static String alipayCertifyInitEx(String certName, String certNO,AlipayOpenapiHelper alipayOpenapiHelper) {

        AlipayOpenapi alipayOpenapi = alipayOpenapiHelper.findAlipayOpenapi(NEW_APP_ID);

        AlipayClient alipayClient = new DefaultAlipayClient(ALI_URL, NEW_APP_ID, alipayOpenapi.getPrivateKey(), FORMAT, CHARSET, alipayOpenapi.getAliPubicKey(), SIGN_TYPE);

        AlipayUserCertifyOpenInitializeRequest request = new AlipayUserCertifyOpenInitializeRequest();
        //构造身份信息json对象
        JSONObject identityObj = new JSONObject();
        //身份类型,必填,详细取值范围请参考接口文档说明
        identityObj.put("identity_type", "CERT_INFO");
        //证件类型,必填,详细取值范围请参考接口文档说明
        identityObj.put("cert_type", "IDENTITY_CARD");
        //真实姓名,必填
        identityObj.put("cert_name", certName);
        //证件号码,必填
        identityObj.put("cert_no", certNO);

        //构造商户配置json对象
        JSONObject merchantConfigObj = new JSONObject();
        // 设置回调地址,必填. 如果需要直接在支付宝APP里面打开回调地址使用alipay协议,参考下面的案例:appId用固定值 20000067,url替换为urlEncode后的业务回跳地址
        merchantConfigObj.put("return_url", "yohobuyufo://www.yohobuy.com/ufo");

        //构造身份认证初始化服务业务参数数据
        JSONObject bizContentObj = new JSONObject();
        //商户请求的唯一标识,推荐为uuid,必填
        bizContentObj.put("outer_order_no", UUID.randomUUID());
        bizContentObj.put("biz_code", "CERT_PHOTO");
        bizContentObj.put("identity_param", identityObj);
        bizContentObj.put("merchant_config", merchantConfigObj);
        request.setBizContent(bizContentObj.toString());

        //发起请求
        try {
            AlipayUserCertifyOpenInitializeResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                String certifyId = response.getCertifyId();
                logger.info("AlipayCertHelper.alipayCertifyInit: init result. certID is {}, certName is {}, certifyId is {}", certNO, certName, certifyId);
                return certifyId;
            }
        }catch (Exception e){
            logger.error("AlipayCertHelper.alipayCertifyInit: Alipay init failed. certID is {}, certName is {}", certNO, certName, e);
        }
        return null;
    }


    public static String alipayCertifyCertify(String certify_id) {
        //获取alipay client
        AlipayClient alipayClient = new DefaultAlipayClient(ALI_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayUserCertifyOpenCertifyRequest request = new AlipayUserCertifyOpenCertifyRequest();

        //设置certifyId
        JSONObject bizContentObj = new JSONObject();
        bizContentObj.put("certify_id", certify_id);
        request.setBizContent(bizContentObj.toString());
        request.setReturnUrl("yohobuyufo://www.yohobuy.com/ufo?certify_id=" + certify_id + "&");
        //生成请求链接,这里一定要使用GET模式
        try {
            AlipayUserCertifyOpenCertifyResponse response = alipayClient.pageExecute(request, "GET");
            if (response.isSuccess()) {
                String certifyUrl = response.getBody();
                logger.info("AlipayCertHelper.alipayCertifyCertify: alipay certify result. certify_id is {}, certifyUrl is {}", certify_id, certifyUrl);
                return certifyUrl;
            }
        }catch (Exception e){
            logger.error("AlipayCertHelper.alipayCertifyCertify: alipay certify failed. certify_id is {}", certify_id);
        }
        return null;
    }

    public static AlipayUserCertifyOpenQueryResponse alipayCertifyResult(String certify_id) throws AlipayApiException {
        //获取alipay client
        AlipayClient alipayClient = new DefaultAlipayClient(ALI_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

        AlipayUserCertifyOpenQueryRequest  request = new AlipayUserCertifyOpenQueryRequest ();
        JSONObject bizContentObj = new JSONObject();
        bizContentObj.put("certify_id", certify_id);//本次申请操作的唯一标识,由开放认证初始化接口调用后生成
        request.setBizContent(bizContentObj.toString());

        return alipayClient.execute(request);

    }

    public static AlipayUserCertifyOpenQueryResponse alipayCertifyResultEx(String certify_id, AlipayOpenapiHelper alipayOpenapiHelper) throws AlipayApiException {
        AlipayOpenapi alipayOpenapi = alipayOpenapiHelper.findAlipayOpenapi(NEW_APP_ID);

        //获取alipay client
        AlipayClient alipayClient = new DefaultAlipayClient(ALI_URL, NEW_APP_ID, alipayOpenapi.getPrivateKey(), FORMAT, CHARSET, alipayOpenapi.getAliPubicKey(), SIGN_TYPE);

        AlipayUserCertifyOpenQueryRequest  request = new AlipayUserCertifyOpenQueryRequest ();
        JSONObject bizContentObj = new JSONObject();
        bizContentObj.put("certify_id", certify_id);//本次申请操作的唯一标识,由开放认证初始化接口调用后生成
        request.setBizContent(bizContentObj.toString());

        return alipayClient.execute(request);

    }


    public static void main(String[] args) throws AlipayApiException {
        String certifyId = AlipayCertHelper.alipayCertifyInitEx("邓新飞", "340604198806232218", null);
        String certifyUrl = AlipayCertHelper.alipayCertifyCertify(certifyId);
        AlipayCertHelper.alipayCertifyResult(certifyId);
        System.err.println(certifyUrl);
    }


    public static String alipayCertifyCertifyEx(String certifyId, AlipayOpenapiHelper alipayOpenapiHelper) {

        AlipayOpenapi alipayOpenapi = alipayOpenapiHelper.findAlipayOpenapi(NEW_APP_ID);

        //获取alipay client
        AlipayClient alipayClient = new DefaultAlipayClient(ALI_URL, NEW_APP_ID, alipayOpenapi.getPrivateKey(), FORMAT, CHARSET, alipayOpenapi.getAliPubicKey(), SIGN_TYPE);
        AlipayUserCertifyOpenCertifyRequest request = new AlipayUserCertifyOpenCertifyRequest();

        //设置certifyId
        JSONObject bizContentObj = new JSONObject();
        bizContentObj.put("certify_id", certify_id);
        request.setBizContent(bizContentObj.toString());
        request.setReturnUrl("yohobuyufo://www.yohobuy.com/ufo?certify_id=" + certify_id + "&");
        //生成请求链接,这里一定要使用GET模式
        try {
            AlipayUserCertifyOpenCertifyResponse response = alipayClient.pageExecute(request, "GET");
            if (response.isSuccess()) {
                String certifyUrl = response.getBody();
                logger.info("AlipayCertHelper.alipayCertifyCertify: alipay certify result. certify_id is {}, certifyUrl is {}", certify_id, certifyUrl);
                return certifyUrl;
            }
        }catch (Exception e){
            logger.error("AlipayCertHelper.alipayCertifyCertify: alipay certify failed. certify_id is {}", certify_id);
        }
        return null;
    }
}