先贴代码:
处理支付得Contoller
================================================================
import java.io.IOException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ejun.crud.bean.H5ScencInfo;
import com.ejun.crud.bean.H5ScencInfo.H5;
import com.ejun.crud.test.Demo.RandomType;
import com.jpay.ext.kit.HttpKit;
import com.jpay.ext.kit.IpKit;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.ext.kit.StrKit;
import com.jpay.util.HttpUtils;
import com.jpay.weixin.api.WxPayApi.TradeType;
import com.jpay.weixin.api.WxPayApiConfig;
import com.jpay.weixin.api.WxPayApiConfigKit;
@Controller
public class OrderWxpay {
/**
*
*/
private static final long serialVersionUID = 1L;
private Logger log = LoggerFactory.getLogger(this.getClass());
private static String mchID="1480406272";
private static String appID="wx92ee752a208a5698";
private static String partnerKey="JIEXING2750898252yibeinuomeng668";
private static String notify_url="www.yibeinuomeng.com/pay_notify";
private static final String UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
/*=====================随机数生成=====================*/
// 随机字符串
private static final String _INT = "0123456789";
private static final String _STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final String _ALL = _INT + _STR;
private static final Random RANDOM = new Random();
/**
* 微信H5 支付
*/
/**
* 微信H5 支付--------------------好使
* 注意:必须再web页面中发起支付且域名已添加到开发配置中
* @throws IOException
* @throws ServletException
*/
@RequestMapping(value ="/paytest",method = {RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public void wapPay(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
String ip = IpKit.getRealIp(request);
if (StrKit.isBlank(ip)) {
ip = "127.0.0.1";
}
ip = "49.66.24.130";
H5ScencInfo sceneInfo = new H5ScencInfo();
H5 h5_info = new H5();
h5_info.setType("Wap");
//此域名必须在商户平台--"产品中心"--"开发配置"中添加
String randomstring=random(32, RandomType.ALL);
//随机数
String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
System.out.println("随机数"+randomstring);
h5_info.setWap_url("http://www.yibeinuomeng.com");
h5_info.setWap_name("伊贝诺萌");
sceneInfo.setH5_info(h5_info);
WxPayApiConfig wxapi=WxPayApiConfig.New();
wxapi.setAppId(appID);
wxapi.setAttach("伊贝诺萌商品支付");
wxapi.setBody("yibeinuomeng.com");
wxapi.setSpbillCreateIp(ip);
wxapi.setTotalFee("520");
wxapi.setTradeType(TradeType.MWEB);
wxapi.setNotifyUrl(notify_url);
wxapi.setOutTradeNo(String.valueOf(System.currentTimeMillis()));
wxapi.setNonceStr(nonce_str);
wxapi.setSceneInfo(h5_info.toString());
wxapi.setMchId(mchID);
wxapi.setAppId(appID);
wxapi.setPaternerKey(partnerKey);
wxapi.setNonceStr(randomstring);
Map<String, String> params = new TreeMap<String, String>();
params.put("appid", wxapi.getAppId());
params.put("body", wxapi.getBody());
params.put("mch_id", wxapi.getMchId());
params.put("nonce_str", wxapi.getNonceStr());
params.put("notify_url", wxapi.getNotifyUrl());
params.put("out_trade_no", wxapi.getOutTradeNo());
params.put("spbill_create_ip", wxapi.getSpbillCreateIp());
params.put("total_fee", wxapi.getTotalFee());
params.put("trade_type", wxapi.getTradeType().toString());
String sign=createSign("UTF-8", params, "JIEXING2750898252yibeinuomeng668");
params.put("sign", sign);
String data=PaymentKit.toXml(params);
System.out.println(params+"AAAAAAAAAAAA");
System.out.println(data);
String xmlResult = HttpUtils.post(UNIFIEDORDER_URL,data );
System.out.println(xmlResult);
Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
String return_code = result.get("return_code");
String return_msg = result.get("return_msg");
if (!PaymentKit.codeIsOK(return_code)) {
log.error("return_code>"+return_code+" return_msg>"+return_msg);
throw new RuntimeException(return_msg);
}
String result_code = result.get("result_code");
if (!PaymentKit.codeIsOK(result_code)) {
log.error("result_code>"+result_code+" return_msg>"+return_msg);
throw new RuntimeException(return_msg);
}
// 以下字段在return_code 和result_code都为SUCCESS的时候有返回
String prepay_id = result.get("prepay_id");
String mweb_url = result.get("mweb_url");
System.out.println("prepay_id:"+prepay_id+" mweb_url:"+mweb_url);
try {
response.sendRedirect(mweb_url);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 随机数生成
* @param count
* @return {String}
*/
public static String random(int count, RandomType randomType) {
if (count == 0) return "";
if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
char[] buffer = new char[count];
for (int i = 0; i < count; i++) {
if (randomType.equals(RandomType.INT)) {
buffer[i] = _INT.charAt(RANDOM.nextInt(_INT.length()));
} else if (randomType.equals(RandomType.STRING)) {
buffer[i] = _STR.charAt(RANDOM.nextInt(_STR.length()));
}else {
buffer[i] = _ALL.charAt(RANDOM.nextInt(_ALL.length()));
}
}
return new String(buffer);
}
/**
* 微信支付签名算法sign
* @param characterEncoding
* @param params
* @return
*/
@SuppressWarnings("unchecked")
public static String createSign(String characterEncoding,Map<String, String> params,String key){
StringBuffer sb = new StringBuffer();
Set es = params.entrySet();//所有参与传参的参数按照accsii排序(升序)
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + key);
String sign = MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
@RequestMapping(value = "/pay_notify",method={RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public String pay_notify(HttpServletRequest request) {
// 支付结果通用通知文档: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7
String xmlMsg = HttpKit.readData(request);
System.out.println("支付通知="+xmlMsg);
Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
// String appid = params.get("appid");
// //商户号
// String mch_id = params.get("mch_id");
String result_code = params.get("result_code");
// String openId = params.get("openid");
// //交易类型
// String trade_type = params.get("trade_type");
// //付款银行
// String bank_type = params.get("bank_type");
// // 总金额
// String total_fee = params.get("total_fee");
// //现金支付金额
// String cash_fee = params.get("cash_fee");
// // 微信支付订单号
// String transaction_id = params.get("transaction_id");
// // 商户订单号
// String out_trade_no = params.get("out_trade_no");
// // 支付完成时间,格式为yyyyMMddHHmmss
// String time_end = params.get("time_end");
/以下是附加参数///
String attach = params.get("attach");
// String fee_type = params.get("fee_type");
// String is_subscribe = params.get("is_subscribe");
// String err_code = params.get("err_code");
// String err_code_des = params.get("err_code_des");
// 注意重复通知的情况,同一订单号可能收到多次通知,请注意一定先判断订单状态
// 避免已经成功、关闭、退款的订单被再次更新
// Order order = Order.dao.getOrderByTransactionId(transaction_id);
// if (order==null) {
if(PaymentKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPaternerKey())){
if (("SUCCESS").equals(result_code)) {
//更新订单信息
log.warn("更新订单信息:"+attach);
//发送通知等
Map<String, String> xml = new HashMap<String, String>();
xml.put("return_code", "SUCCESS");
xml.put("return_msg", "OK");
return PaymentKit.toXml(xml);
}
}
// }
return null;
}
}
============================================================================