支付宝小程序支付和获取用户相关信息

这些包是自定义的,不影响业务逻辑。可以自行处理

消息类别
import com.cat.common.bean.EMsg;
业务异常
import com.cat.common.exception.RequestException;
JSON 格式化工具
import com.cat.common.json.RJson;

字符串判断工具
import com.cat.common.lang.RString;
获取配置文件
import com.cat.common.listener.RSystemConfig;

package com.smk.mall.service.alipay;

import java.util.HashMap;
import java.util.Map;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipayEncrypt;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayTradeCancelRequest;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayUserGradeQueryRequest;
import com.alipay.api.request.AlipayUserPointDeductRequest;
import com.alipay.api.request.AlipayUserPointRefundRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayTradeCancelResponse;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayUserGradeQueryResponse;
import com.alipay.api.response.AlipayUserPointDeductResponse;
import com.alipay.api.response.AlipayUserPointRefundResponse;
import com.cat.common.bean.EMsg;
import com.cat.common.exception.RequestException;
import com.cat.common.json.RJson;
import com.cat.common.lang.RString;
import com.cat.common.listener.RSystemConfig;

public class AlipayUtils {

	private AlipayClient alipayClient;

	private String alipayPublicKey;

	private String aesKey;

	public AlipayUtils(String appId, String appPrivateKey, String alipayPublicKey, String aesKey) {
		this.alipayPublicKey = alipayPublicKey;
		this.aesKey = aesKey;
		
		String serverUrl = RSystemConfig.getValue("alipayUrl");
		if (RString.isBlank(serverUrl)) {
			serverUrl = "https://openapi.alipay.com/gateway.do";
		}
		alipayClient = new DefaultAlipayClient(serverUrl, appId, appPrivateKey, "json", "utf-8", alipayPublicKey,
				"RSA2");
		// alipayClient =new DefaultAlipayClient(serverUrl, appId, appPrivateKey,
		// "json", "utf-8", alipayPublicKey,
		// "RSA2", encryptKey, "AES");
	}

	public AlipayClient getClient() {
		if (alipayClient == null) {
			throw new RequestException(EMsg.Fail, "支付宝支付未实例化");
		}
		return alipayClient;
	}


	/**
	   *   下订单
	 * @param alipayId   用户支付宝ID
	 * @param outTradeNo  业务的唯一订单号
	 * @param money  金额  元
	 * @param desc  订单描述
	 * @param notifyUrl   异步通知地址
	 * @return
	 */
	public String createNo(String alipayId, String outTradeNo, double money, String desc, String notifyUrl) {
		AlipayTradeCreateRequest re = new AlipayTradeCreateRequest();
		re.setNotifyUrl(notifyUrl);

		Map<String, Object> m = new HashMap<String, Object>();
		m.put("out_trade_no", outTradeNo);// 订单号
		m.put("total_amount", money / 100);// 总金额元
		m.put("subject", desc);// 订单描述
		m.put("timeout_express", "50m");// 50分钟自动关闭
		m.put("buyer_id", alipayId); //

		Map<String, Object> extendParams = new HashMap<String, Object>();
		extendParams.put("sys_service_provider_id", "2088911959866152");
		m.put("extend_params", extendParams);// 订单号

		re.setBizContent(RJson.getJsonStr(m));
		try {
			AlipayTradeCreateResponse rep = getClient().execute(re);
			if (rep.isSuccess()) {
				return rep.getTradeNo();//成功后返回支付宝订单号
			} else {
				throw new RequestException(EMsg.Fail, rep.getSubMsg());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new RequestException(EMsg.Fail, e.getErrMsg());
		}

	}

	/**
	 *  订单关闭
	 * @param trade_no  支付宝返回的订单号
	 * @param outTradeNo  业务自己的订单号  二选一
	 * @return
	 */
	public boolean closeOrder(String trade_no, String outTradeNo) {
		AlipayTradeCloseRequest re = new AlipayTradeCloseRequest();

		Map<String, Object> m = new HashMap<String, Object>();
		m.put("trade_no", trade_no);
		m.put("out_trade_no", outTradeNo);
		re.setBizContent(RJson.getJsonStr(m));

		try {
			AlipayTradeCloseResponse rep = getClient().execute(re);
			if (rep.isSuccess()) {
				return true;
			} else {
				throw new RequestException(EMsg.Fail, rep.getSubMsg());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new RequestException(EMsg.Fail, e.getErrMsg());
		}
	}

	/**
	 *   订单退款
	 * @param tradeNo   支付宝返回的订单号
	 * @param outTradeNo 业务自己的订单号  二选一
	 * @param money   需要退多少钱
	 * @param refundNo  唯一的退款订单号,业务自己定义
	 */
	public void refundOrder(String tradeNo, String outTradeNo, double money, String refundNo) {
		AlipayTradeRefundRequest re = new AlipayTradeRefundRequest();

		Map<String, Object> m = new HashMap<String, Object>();
		m.put("trade_no", tradeNo);// 订单号
		m.put("out_trade_no", outTradeNo);// 总金额元
		m.put("refund_amount", money / 100);// 总金额元
		m.put("out_request_no", refundNo);
		re.setBizContent(RJson.getJsonStr(m));

		try {
			AlipayTradeRefundResponse rep = getClient().execute(re);
			if (rep.isSuccess()) {
				return;
			} else {
				throw new RequestException(EMsg.Fail, rep.getSubMsg());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new RequestException(EMsg.Fail, e.getErrMsg());
		}
	}

	/**
	 *  退款查询  
	 * @param trade_no 支付宝返回的订单号
	 * @param orderNo  业务自己的订单号  二选一
	 * @param refundNo  退款的订单号
	 * @return
	 */
	public String refundQuery(String trade_no, String orderNo, String refundNo) {
		AlipayTradeFastpayRefundQueryRequest re = new AlipayTradeFastpayRefundQueryRequest();

		Map<String, Object> m = new HashMap<String, Object>();
		m.put("trade_no", trade_no);// 订单号
		m.put("out_trade_no", orderNo);// 订单号
		m.put("out_request_no", refundNo);
		re.setBizContent(RJson.getJsonStr(m));

		try {
			AlipayTradeFastpayRefundQueryResponse rep = getClient().execute(re);
			if (rep.isSuccess()) {
				return "TRADE_SUCCESS";
			} else if (rep.getSubCode().equalsIgnoreCase("ACQ.TRADE_NOT_EXIST")) {
				//统一返回结果状态,订单不存在的情况
				return "TRADE_NOT_EXIST";
			} else {
				throw new RequestException(EMsg.Fail, rep.getSubMsg());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new RequestException(EMsg.Fail, e.getErrMsg());

		}
	}

	/**
	 * 撤销交易
	 * 
	 * @param trade_no 支付宝返回的订单号
	 * @param orderNo  业务自己的订单号  二选一
	 * @return
	 */
	public String cancelOrder(String trade_no, String orderNo) {
		AlipayTradeCancelRequest re = new AlipayTradeCancelRequest();

		Map<String, Object> m = new HashMap<String, Object>();
		m.put("trade_no", trade_no);// 订单号
		m.put("out_trade_no", orderNo);// 总金额元
		re.setBizContent(RJson.getJsonStr(m));

		try {
			AlipayTradeCancelResponse rep = getClient().execute(re);
			if (rep.isSuccess()) {
				return rep.getAction();
			} else {
				throw new RequestException(EMsg.Fail, rep.getSubMsg());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new RequestException(EMsg.Fail, e.getErrMsg());
		}
	}

	/**
	 * 交易查询
	 * 
	 * @param trade_no 支付宝返回的订单号
	 * @param orderNo  业务自己的订单号  二选一
	 * @return WAIT_BUYER_PAY TRADE_CLOSED TRADE_SUCCESS TRADE_FINISHED
	 *         TRADE_NOT_EXIST
	 */
	public String orderQuery(String trade_no, String outTradeNo) {
		AlipayTradeQueryRequest re = new AlipayTradeQueryRequest();
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("trade_no", trade_no);// 订单号
		m.put("out_trade_no", outTradeNo);// 总金额元
		re.setBizContent(RJson.getJsonStr(m));

		try {
			AlipayTradeQueryResponse rep = getClient().execute(re);
			if (rep.isSuccess()) {
				/*
				 * if("WAIT_BUYER_PAY".equalsIgnoreCase(rep.getTradeStatus())) { //未付款 }else
				 * if("TRADE_CLOSED".equalsIgnoreCase(rep.getTradeStatus())) { //交易关闭 }else
				 * if("TRADE_SUCCESS".equalsIgnoreCase(rep.getTradeStatus())) { //已支付 }else
				 * if("TRADE_FINISHED".equalsIgnoreCase(rep.getTradeStatus())) { //交易结束,不可退款 }
				 */
				return rep.getTradeStatus();
			} else if (rep.getSubCode().equalsIgnoreCase("ACQ.TRADE_NOT_EXIST")) {
				return "TRADE_NOT_EXIST";  //订单不存在
			} else {
				throw new RequestException(EMsg.Fail, rep.getSubMsg());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new RequestException(EMsg.Fail, e.getErrMsg());
		}
	}

	/**
	 * 签名校验
	 * @param paramsMap
	 * @return
	 */
	public boolean checkNotify(Map<String, String> paramsMap) {
		try {
			return AlipaySignature.rsaCheckV1(paramsMap, this.alipayPublicKey, "utf-8", "RSA2");
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 用户授权 信息获取支付宝ID
	 * @param code
	 * @return
	 */
	public String oauthToken(String code) {
		AlipaySystemOauthTokenRequest re = new AlipaySystemOauthTokenRequest();
		re.setGrantType("authorization_code");
		re.setCode(code);

		try {
			AlipaySystemOauthTokenResponse rep = getClient().execute(re);
			if (rep.isSuccess()) {
				return rep.getUserId();
			} else {
				throw new RequestException(EMsg.Fail, rep.getSubMsg());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new RequestException(EMsg.Fail, e.getErrMsg());
		}
	}
	
	/**
	 * 用户授权 信息获取token
	 * @param code
	 * @return
	 */
	public String getTokenOauthToken(String code) {
		AlipaySystemOauthTokenRequest re = new AlipaySystemOauthTokenRequest();
		re.setGrantType("authorization_code");
		re.setCode(code);

		try {
			AlipaySystemOauthTokenResponse rep = getClient().execute(re);
			if (rep.isSuccess()) {
				return rep.getAccessToken();
			} else {
				throw new RequestException(EMsg.Fail, rep.getSubMsg());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new RequestException(EMsg.Fail, e.getErrMsg());
		}
	}

	/**
	 * 解析授权的手机号
	 * @param str
	 * @return
	 */
	public String getPhoneNum(String str) {
		// 1. 获取验签和解密所需要的参数
		Map<String, Object> openapiResult = RJson.parseJson2Map(str);
		String signType = "RSA2";
		String charset = "UTF-8";
		String encryptType = "AES";
		String sign = RString.toString(openapiResult.get("sign"));//
		String content = RString.toString(openapiResult.get("response"));//

		// 如果密文的
		boolean isDataEncrypted = !content.startsWith("{");
		boolean signCheckPass = false;

		// 2. 验签
		String signContent = content;
		// 如果是加密的报文则需要在密文的前后添加双引号
		if (isDataEncrypted) {
			signContent = "\"" + signContent + "\"";
		}
		try {
			signCheckPass = AlipaySignature.rsaCheck(signContent, sign, this.alipayPublicKey, charset, signType);
		} catch (AlipayApiException e) {
			// 验签异常, 日志
		}
		if (!signCheckPass) {
			// 验签不通过(异常或者报文被篡改),终止流程(不需要做解密)
			throw new RequestException(EMsg.Fail, "验签失败");
		}

		// 3. 解密
		String plainData = null;
		if (isDataEncrypted) {
			try {
				plainData = AlipayEncrypt.decryptContent(content, encryptType, this.aesKey, charset);
			} catch (AlipayApiException e) {
				// 解密异常, 记录日志
				throw new RequestException(EMsg.Fail, "解密异常");
			}
		} else {
			plainData = content;
		}
		Map<String, Object> phoneMap = RJson.parseJson2Map(plainData);
		return RString.toString(phoneMap.get("mobile"));
	}

	/**
	 * 获取用户的蚂蚁积分
	 * @param accessToken
	 * @return
	 */
	public Long UserGrade(String accessToken) {
		AlipayUserGradeQueryRequest request = new AlipayUserGradeQueryRequest();
		try {
			AlipayUserGradeQueryResponse rep = getClient().execute(request, accessToken);
			if (rep.isSuccess()) {
				return rep.getBalance();
			} else {
				throw new RequestException(EMsg.Fail, rep.getSubMsg());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new RequestException(EMsg.Fail, e.getErrMsg());
		}

	}

	/**
	 * 使用蚂蚁积分
	 * @param accessToken
	 * @param benefitId
	 * @param orderDetaiNo
	 * @return
	 */
	public boolean userPointDeduct(String accessToken, String benefitId, String orderDetaiNo) {
		AlipayUserPointDeductRequest request = new AlipayUserPointDeductRequest();
		try {
			request.setBizContent("{\"benefit_id\":\"" + benefitId + "\",\"out_biz_no\":\"" + orderDetaiNo + "\"}");
			AlipayUserPointDeductResponse response = getClient().execute(request, accessToken);
			if (response.isSuccess()) {
				return true;
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new RequestException(EMsg.Fail, e.getErrMsg());
		}
		return false;
	}

	/**
	 * 蚂蚁积分退款
	 * @param alipayId
	 * @param orderDetaiNo
	 * @return
	 */
	public boolean userPointRefund(String alipayId,String orderDetaiNo) {
		AlipayUserPointRefundRequest request = new AlipayUserPointRefundRequest();
		try {
			request.setBizContent("{\"out_biz_no\":\""+orderDetaiNo+"\", \"user_id\":\""+alipayId+"\"}");
			AlipayUserPointRefundResponse response = alipayClient.execute(request);
			if (response.isSuccess()) {
				return true;
			} 
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new RequestException(EMsg.Fail, e.getErrMsg());
		}
		return false;
	}

	public static void main(String[] args) {
		c();
	}
	
	private static void c() {
		AlipayUtils s = getHzCard();
		String dd = s.orderQuery("", "12019092212143499611");
		System.out.println(dd);
		//String dds = s.refundQuery("", "21201909221214349961", "212019092212143499611472");
		//System.out.println(dds);
	}

	public  static AlipayUtils getHzCard() {
		String appId = "支付宝ID";
		String privateKey = "业务私钥=";
		String alipay_public_key = "支付宝公钥";
		String aesEncryptKey = "加密串密钥==";

		return  new AlipayUtils(appId, privateKey, alipay_public_key, aesEncryptKey);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值