Java微信支付之服务号支付代码示例
Java微信支付之服务号支付实现,网上的java微信支付sdk和Demo基本上是水的,看着头疼所以我决心自己开始写Java微信支付之公众号支付,多的不说见下面源码,为了方便使用我分别用了两个Servlet,一个是统一下单UnifiedorderServlet,一个是支付回调PayCallBackServlet,你们可以自己封装。
一是统一下单UnifiedorderServlet:
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.io.PrintWriter;
importjava.io.UnsupportedEncodingException;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjava.security.MessageDigest;
importjava.security.NoSuchAlgorithmException;
importjava.util.Random;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.http.ParseException;
importorg.apache.http.client.ClientProtocolException;
importorg.json.JSONArray;
importorg.json.JSONException;
importorg.json.JSONML;
importorg.json.JSONObject;
publicclassUnifiedorderServletextendsHttpServlet{
privatestaticfinallongserialVersionUID=1L;
privatestaticfinalStringappid="";//找微信
privatestaticfinalStringmch_id="";//找微信
publicstaticfinalStringapi_key="";//找微信
privatestaticfinalStringtrade_type="JSAPI";//写死
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
response.setContentType("text/html;charset=utf-8");
PrintWriterout=response.getWriter();
JSONObjectjso=newJSONObject();
doublemoney=0.01;
StringopenId="",out_trade_no="",body="测试",ip="";
try{
out.print(execute(out_trade_no,body,openId,money,ip,jso).toString());
}catch(JSONExceptione){
e.printStackTrace();
}
out.flush();
out.close();
}
/**
*微信服务号统一下单支付
*
*@paramout_trade_no
*订单号
*@parambody
*标题
*@paramopenId
*用户的openId
*@parammoney
*支付金额
*@paramip
*客户端ip
*@paramrequest
*HttpServletRequest
*@return
*@throwsJSONException
*/
publicJSONObjectexecute(Stringout_trade_no,Stringbody,StringopenId,doublemoney,Stringip,JSONObjectjso)throwsJSONException{
StringBuilderxml=newStringBuilder();
Stringnotify_url="https://test.com/payCallBack";//支付回调地址
Stringprepay_id="",sign="",charset="UTF-8",nonce_str="";
try{
StringweixinMoney=newjava.text.DecimalFormat("#").format(money*100);//微信是以分为单位的所以要乘以100
nonce_str=getRandomString(32);
xml.append("appid=").append(appid).append("&body=").append(newString(body.getBytes(charset),charset));//处理中文
xml.append("&mch_id=").append(mch_id).append("&nonce_str=").append(nonce_str);
xml.append("¬ify_url=").append(notify_url).append("&openid=").append(openId);
xml.append("&out_trade_no=").append(out_trade_no).append("&spbill_create_ip=").append(ip);
xml.append("&total_fee=").append(weixinMoney).append("&trade_type=").append(trade_type).append("&key=").append(api_key);
sign=MD5Purity(xml.toString());
//System.out.println(xml);
xml.delete(0,xml.length());
xml.append("");
xml.append("").append(appid).append("");
xml.append("").append(body).append("");
xml.append("").append(mch_id).append(" ");
xml.append("").append(nonce_str).append(" ");
xml.append("").append(openId).append(" ");
xml.append("").append(notify_url).append(" ");
xml.append("").append(out_trade_no).append(" ");
xml.append("").append(ip).append(" ");
xml.append("").append(weixinMoney).append(" ");
xml.append("").append(trade_type).append(" ");
xml.append("").append(sign).append(" ");
xml.append(" ");
HttpURLConnectionconn=(HttpURLConnection)newURL("https://api.mch.weixin.qq.com/pay/unifiedorder").openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","text/xml");
conn.setRequestProperty("Charset",charset);
OutputStreamos=conn.getOutputStream();
os.write(xml.toString().getBytes(charset));
xml.delete(0,xml.length());
os.close();
intresponseCode=conn.getResponseCode();
InputStreamReaderin=null;
BufferedReaderbr=null;
if(responseCode==200){
in=newInputStreamReader(conn.getInputStream(),charset);
br=newBufferedReader(in);
StringretData=null;
while((retData=br.readLine())!=null)
xml.append(retData);
JSONArraychildNodes=JSONML.toJSONObject(xml.toString()).getJSONArray("childNodes");
intlen=childNodes.length()-1;
for(inti=len;i>-1;i--){
JSONObjectjs=childNodes.getJSONObject(i);
if(js.get("tagName").equals("prepay_id")){
prepay_id=js.getJSONArray("childNodes").getString(0);
break;
}
}
}
if(in!=null)
in.close();
if(br!=null)
br.close();
conn.disconnect();
//----------------------------------给h5返回的数据
StringtimeStamp=System.currentTimeMillis()+"";
timeStamp=timeStamp.substring(0,10);//微信只要精确到秒
nonce_str=getRandomString(32);
jso.put("appId",appid);
jso.put("nonceStr",nonce_str);
jso.put("package","prepay_id="+prepay_id);
jso.put("signType","MD5");
jso.put("timeStamp",timeStamp);
xml.delete(0,xml.length());
xml.append("appId=").append(appid);
xml.append("&nonceStr=").append(nonce_str);
xml.append("&package=").append(jso.getString("package"));
xml.append("&signType=").append(jso.getString("signType"));
xml.append("&timeStamp=").append(timeStamp);
xml.append("&key=").append(api_key);
sign=MD5Purity(newString(xml.toString().getBytes(charset),charset));
jso.put("paySign",sign);
//返回的数据主要用在这地方https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6
//----------------------------------给h5返回的数据
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(ParseExceptione){
e.printStackTrace();
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returnjso;
}
/**
*MD5
*
*@paramplainText
*@return
*/
publicStringMD5Purity(StringplainText){
try{
MessageDigestmd=MessageDigest.getInstance("MD5");
md.update(plainText.getBytes("utf-8"));
byteb[]=md.digest();
inti;
StringBufferbuf=newStringBuffer("");
for(intoffset=0;offset
二是支付回调PayCallBackServlet:
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.io.UnsupportedEncodingException;
importjava.security.MessageDigest;
importjava.security.NoSuchAlgorithmException;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.json.JSONArray;
importorg.json.JSONException;
importorg.json.JSONML;
importorg.json.JSONObject;
publicclassPayCallBackServletextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
response.setContentType("text/html;charset=utf-8");
PrintWriterout=response.getWriter();
out.print(doWxServer(request));
out.flush();
out.close();
}
/**
*处理微信回调
*
*@paramrequest
*@return
*@throwsServletException
*@throwsIOException
*/
publicStringdoWxServer(HttpServletRequestrequest){
System.out.println("微信服务号支付回调");
StringinputLine;
StringBuildernotityXml=newStringBuilder();
BufferedReaderbufferedReader=null;
try{
bufferedReader=request.getReader();
while((inputLine=bufferedReader.readLine())!=null)
notityXml.append(inputLine);
if(bufferedReader!=null)
bufferedReader.close();
if(notityXml.length()<10){
return"fail";
}
Stringappid="",total_fee="",bank_type="",cash_fee="",fee_type="",is_subscribe="",mch_id="",nonce_str="";
Stringout_trade_no="",transaction_id="",openid="",sign="",result_code="",return_code="",time_end="",trade_type="";
JSONArrayresult=JSONML.toJSONObject(notityXml.toString()).getJSONArray("childNodes");
intlen=result.length();
for(inti=0;i ";//成功后给微信返回数据
}catch(JSONExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
return"fail";
}
/**
*MD5
*
*@paramplainText
*@return
*/
publicStringMD5Purity(StringplainText){
try{
MessageDigestmd=MessageDigest.getInstance("MD5");
md.update(plainText.getBytes("utf-8"));
byteb[]=md.digest();
inti;
StringBufferbuf=newStringBuffer("");
for(intoffset=0;offset
大功告成
总结
以上就是本文关于Java微信支付之服务号支付代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:快速理解Java设计模式中的组合模式、Java编程接口调用的作用及代码分享、浅谈java中字符串数组、字符串、整形之间的转换等,有什么问题可以随时留言,小编会及时回复大家的。感谢朋友们对本站的支持!