package com.qxwljs.app.cms.component.app.plugin;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.qxwljs.app.cms.payment.model.BaseOrder;
import com.qxwljs.app.cms.payment.model.PayCfg;
import com.qxwljs.app.cms.payment.model.PayEnable;
import com.qxwljs.app.cms.payment.plugin.AbstractPaymentPlugin;
import com.qxwljs.app.cms.payment.plugin.IPaymentEvent;
import com.qxwljs.app.cms.payment.plugin.PaySuccessProcessorFactory;
import com.qxwljs.app.cms.payment.service.IBaseOrderManager;
import com.qxwljs.app.cms.payment.util.PayUtil;
import com.qxwljs.framework.context.webcontext.ThreadContextHolder;
import com.qxwljs.framework.util.JsonUtil;
import com.qxwljs.jxp.SystemSetting;
import com.qxwljs.jxp.resource.model.JxpSite;
@SuppressWarnings("unchecked")
@Component
public class AppAliPayPlugin extends AbstractPaymentPlugin implements
IPaymentEvent {
public static final String OPENID_SESSION_KEY = "weixin_openid";
public static Random r = new Random();
@Autowired
private IBaseOrderManager orderManager;
@Override
public String onPay(PayCfg payCfg, PayEnable order) {
AlipayTradeAppPayResponse response = null;
try {
String out_trade_no = order.getSn(); // 商户网站订单
String notify_url = this.getCallBackUrl(payCfg, order);
// 需http://格式的完整路径,不能加%sid=123这类自定义参数
// 商户订单号
out_trade_no = new String(out_trade_no.getBytes("ISO-8859-1"), "UTF-8");
// 商户网站订单系统中唯一订单号,必填
String sitename = JxpSite.getInstance().getSitename();
// 订单名称
String subject = sitename + "订单";
// subject = new String(subject.getBytes("ISO-8859-1"), "UTF-8");
// 必填
String body = ("订单:" + out_trade_no);
// body = new String(body.getBytes("ISO-8859-1"), "UTF-8");
// 付款金额
String price = new String(String.valueOf(order.getNeedPayMoney()).getBytes("ISO-8859-1"), "UTF-8");
//String price = "0.01";
Map
String app_id = cfgparams.get("app_id");
String private_key = cfgparams.get("private_key");
String public_key = cfgparams.get("public_key");
//实例化客户端
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", app_id, private_key, "json", "utf-8", public_key, "RSA2");
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay
AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
model.setBody(body);
model.setSubject(subject);
model.setOutTradeNo(out_trade_no);
model.setTimeoutExpress("30m");
model.setTotalAmount(price);
model.setProductCode("QUICK_MSECURITY_PAY");
request.setBizModel(model);
request.setNotifyUrl(notify_url);
try {
//这里和普通的接口调用不同,使用的是sdkExecute
response = alipayClient.sdkExecute(request);
System.out.println();//就是orderString 可以直接给客户端请求,无需再做处理。
} catch (AlipayApiException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Map
map.put("orderInfo", response.getBody());
return JsonUtil.MapToJson(map);
}
//成功回调
@Override
public String onCallBack(String ordertype) {
HttpServletRequest request = ThreadContextHolder.getHttpRequest();
System.err.println("--------进入成功回调------------");
//获取支付宝POST过来反馈信息
Map
Map requestParams = request.getParameterMap();
for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i]
: valueStr + values[i] + ",";
}
//乱码解决,这段代码在出现乱码时使用。
//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
params.put(name, valueStr);
}
//切记alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。
//boolean AlipaySignature.rsaCheckV1(Map
Map
String public_key = cfgparams.get("public_key");
boolean flag = false;
try {
flag = AlipaySignature.rsaCheckV1(params, public_key, "utf-8","RSA2");
System.err.println("flag------------"+flag);
if(flag){
String sn = request.getParameter("out_trade_no");
String total_fee = request.getParameter("total_amount");
String trade_status = request.getParameter("trade_status");
String trade_no = request.getParameter("trade_no");
String buyer_logon_id = request.getParameter("buyer_id");
BaseOrder order = orderManager.get(sn);
if(order.getNeed_pay_money().equals(Double.valueOf(total_fee))){
if(trade_status.equals("TRADE_SUCCESS") ){
logger.error("status:"+order.getPay_status());
if (null != order && order.getPay_status() == PayUtil.PAY_NO) {
try{
this.paySuccess(sn,trade_no, buyer_logon_id,ordertype);
}catch(Exception e){
e.printStackTrace();
}
}
}
if(trade_status.equals("TRADE_FINISHED")||trade_status.equals("TRADE_SUCCESS")){
this.logger.info("异步校验订单["+sn+"]成功");
return ("success"); //请不要修改或删除
}else {
this.logger.info("异步校验订单["+sn+"]成功");
return ("success"); //请不要修改或删除
}
}
}
} catch (AlipayApiException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
flag = false;
}
return "false";
}
@Override
public String onReturn(String ordertype) {
return null;
}
@Override
public String getId() {
return "appAliPayPlugin";
}
@Override
public String getName() {
return "app支付宝支付";
}
public static String getRandom(){
long num = Math.abs(r.nextLong() % 10000000000L);
String s = String.valueOf(num);
for(int i = 0; i < 10-s.length(); i++){
s = "0" + s;
}
return s;
}
private static int getRandom(int count) {
return (int) Math.round(Math.random() * (count));
}
private static String string = "abcdefghijklmnopqrstuvwxyz1234567890";
private static String getRandomString(int length){
StringBuffer sb = new StringBuffer();
int len = string.length();
for (int i = 0; i < length; i++) {
sb.append(string.charAt(getRandom(len-1)));
}
return sb.toString();
}
/**
* 获取wap的url
* @return
*/
public static String getWapDomainUrl(){
HttpServletRequest request = ThreadContextHolder.getHttpRequest();
int port = request.getServerPort();
String portstr="";
if(port!=80){
portstr=":"+port;
}
String contextPath = request.getContextPath();
if(contextPath.equals("/")){
contextPath="";
}
String severname= SystemSetting.getWap_domain();
String url = "http://"+severname+portstr+contextPath;
return url;
}
public static void main(String args[]) throws AlipayApiException, UnsupportedEncodingException{
}
}