微信扫码支付

微信扫码支付-飞一样的编程
飞一样的编程
擅长邻域:Java,MySQL,Linux,nginx,springboot,mongodb,微信小程序,vue

2022-08-04 23:07:03   33浏览 分类: Java

https://pay.weixin.qq.com/wiki/doc/api/index.html

进入官网

以用户扫描二维码支付为例

image.png

下载demo

image.png

注意微信支付需要证书(这个过程比较麻烦),这个需要去微信平台申请,先交年费300

修改代码

demo不能直接使用需要修改

将demo导入eclipse或者idea,如下

image.png


只有java文件,没有其他的,先来看看他的代码

wxpay.java

image.png


继续往下看看找关键代码,看注释

image.png

以上是生成二维码的接口,如何使用呢??

查看WXPayConfig.java

image.png

需要设置appid等配置参数

那怎么设置呢,这里我们自己写个类GFWXPay.java继承即可

将对应的参数传入封装下单接口(注意证书的位置)

 

public class GFWXPay extends WXPayConfig {

	private byte[] certData;

	public GFWXPay() throws Exception {
		//String certPath = "D:/apiclient_cert.p12";//设置证书位置
		 
		File file = new File(certPath);
		InputStream certStream = new FileInputStream(file);
		this.certData = new byte[(int) file.length()];
		certStream.read(this.certData);
		certStream.close();
	}

	@Override
	String getAppID() {
		return "wxxxxxx";
	}

	@Override
	String getMchID() {
		return "xxxxx";
	}

	@Override
	String getKey() {
		return "xxxxxxx";
	}

	@Override
	InputStream getCertStream() {
		ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
		return certBis;
	}

	@Override
	IWXPayDomain getWXPayDomain() {
		IWXPayDomain iwxPayDomain = new IWXPayDomain() {
			public void report(String domain, long elapsedTimeMillis,
					Exception ex) {

			}

			public DomainInfo getDomain(WXPayConfig config) {
				return new IWXPayDomain.DomainInfo(WXPayConstants.DOMAIN_API,
						true);
			}
		};
		return iwxPayDomain;
	}

	 
     /*jf3q获取微信支付二维码*/
	 public String  getWXQr(String body,String out_trade_no,Double total_fee,String notify_url) throws Exception{
		GFWXPay config = new GFWXPay();
		WXPay wxpay = new WXPay(config);
		Map<String, String> data = new HashMap<String, String>();
		// 根据微信支付api来设置
		data.put("appid", config.getAppID());
		data.put("mch_id", config.getMchID()); // 商户号
										// 扫码支付
		String nonce_str = UUID.randomUUID().toString().replace("-", "").substring(0, 32); 
		data.put("nonce_str",nonce_str ); // 随机字符串小于32位
		
		String sign = WXPayUtil.generateSignature(data, config.getKey()); // 签名
		data.put("sign", sign);
		 
		
		data.put("body", "有偿问答-"+body);
		data.put("out_trade_no",out_trade_no); // 交易号
		
		
		data.put("fee_type", "CNY"); // 默认人民币
		data.put("total_fee", ((int)(total_fee * 100))+""); // 订单总金额
		//data.put("total_fee","1");//测试 
		
		data.put("spbill_create_ip", "xxx.x.x.x"); // 终端ip
		data.put("notify_url", notify_url); // 回调地址
		
		data.put("trade_type", "NATIVE"); // 支付场景 APP 微信app支付 JSAPI 公众号支付 NATIVE
		
		
		

		/** wxPay.unifiedOrder 这个方法中调用微信统一下单接口 */
		Map<String, String> respData = wxpay.unifiedOrder(data);
		System.out.println("**************wx qr pay***********************************");
		System.out.println(respData);
		
		if (respData.get("return_code").equals("SUCCESS")&&respData.get("return_msg").equals("OK")) {
			return respData.get("code_url");//返回二维码的支付参数
		}else return "fail";
		 
	}
	 
	 
}

新建maven web项目

最好自己新建一个web maven项目,将以上代码复制进去,如下图

image.png


写一个支付servlet

package s.jf3q.servlet;
 
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.github.wxpay.sdk.GFWXPay;

@WebServlet("/CreatQrSrvlet.do")
public class CreatQrSrvlet  extends HttpServlet{
	private static final long serialVersionUID = 1L;
	 
	 
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreatQrSrvlet() {
        super();
    }

   
	 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html; charset=utf-8");
		response.setHeader( "Content-type", "text/html;charset=UTF-8" );
	    
		String body=request.getParameter("body");
		String out_trade_no=request.getParameter("out_trade_no");
		String total_fee=request.getParameter("total_fee");
		 
						
 
						try {
//获取支付参数
							String qr=new GFWXPay().getWXQr(body, out_trade_no, Double.parseDouble(total_fee) , "http://115.159.216.132");
							response.getWriter().write(qr);
							response.getWriter().close();
						} catch ( Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						
				 
					 
		 
		 
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)  {
		doGet(request, response);
	}
	
	
	  
}
 

测试

webapp下写个index.tml

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">  
	<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
	<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<script src="qrcode.min.js"></script>
	
<title>Insert title here</title>
</head>
<body>
<form role="form" action="http://localhost:8022/wxpay/CreatQrSrvlet.do" onsubmit="return sub(this);" style="margin-left: 25%;width: 50%;margin-top: 100px;">
  <div class="form-group">
    <label for="name">订单名称</label>
    <input type="text" class="form-control"  name="body"  required="required">
  </div>
   
   <div class="form-group">
    <label for="name">订单号</label>
    <input type="text" class="form-control"  name="out_trade_no"  required="required">
  </div>
  
  <div class="form-group">
    <label for="name">金额</label>
    <input type="number" class="form-control"  name="total_fee"  required="required">
  </div>
  <button type="submit" class="btn btn-default">提交</button>
</form>

<div id="wx_pay_qr" style="width: 200px;height: 200px;"></div>
<script type="text/javascript">
function sub(v){ //利用ajax发送文字到reg,返回信息
	
	$.ajax({
		type:"post",
		url:$(v).attr('action'),
		dataType:"text",
		data:$(v).serialize(),
		success:function(data){
			new QRCode(document.getElementById("wx_pay_qr"), data );//wx_pay_qr是页面的一个id为wx_pay_qr的div,用来显示二维码的
		}
	})
	return false;
}
</script>
</body>
</html>


效果如下:

image.png

后面回调的逻辑和支付宝一样,此处不再赘述

 
 
@WebServlet("/wxnotifyservlet.do")
public class WxNotifyServlet  extends HttpServlet{
	 
     /**
     * @see HttpServlet#HttpServlet()
     */
    public WxNotifyServlet_goldcoin() {
        super();
    }

	 /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=utf-8");
		 response.setHeader( "Content-type", "text/html;charset=UTF-8" );
	      InputStream in = request.getInputStream();
	      BufferedReader br = new BufferedReader( new InputStreamReader( in, "UTF-8" ) );
	      StringBuffer result = new StringBuffer();
	      String line = "";
	      
	      while ( ( line = br.readLine() ) != null ) 
	      {
	        result.append(line);
	      }
	      try {
			Map<String, String> map = WXPayUtil.xmlToMap( result.toString() );
			System.out.println("===问答=微信扫码支付回调=购买金币=====================================");
			String mch_id=map.get("mch_id");
			String appid=map.get("appid");
			
			if(map.get("result_code").equals("SUCCESS")&&map.get("return_code").equals("SUCCESS")&&map.get("return_code").equals("SUCCESS")&&mch_id.equals("xxx")&&appid.equals("xxxx")) {
				String cts=DateUtils.DateTimeToString(new Date());
				
				 
				
				
				 //查询订单等
				if(o!=null&&o.getIs_pay()!=null&&o.getIs_pay().intValue()==0){
					 
					//修改支付状态等其他操作
					response.getWriter().write("success");
					response.getWriter().close();
					
				}
			} else{
				//其他操作,,,, 
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
 

好文章就要一起分享哦!分享海报

此处可发布评论

评论(0

暂无评论,快来写一下吧
客服QQ 1913284695