微信扫码支付

  |   0 评论   |   0 浏览

微信扫码支付

微信扫码支付大致步骤

1.请求微信支付固定地址生成支付二维码,与微信扫码登录不同,微信支付二维码需要下载

2.请求微信订单查询固定地址查询支付状态

3.完成支付业务逻辑

==这里主要记录微信支付流程==

1.业务流程介绍

1、课程支付说明

(1)课程分为免费课程和付费课程,如果是免费课程可以直接观看,如果是付费观看的课程,用户需下单支付后才可以观看

2.生成订单

image-20220130231558997

3.生成微信支付二维码

image-20220130231703561

2.准备工作

引入相关依赖

<!--httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
              <version>4.5.1</version>
        </dependency>
              <!--微信支付-->
        <dependency>
            <groupId>com.github.wxpay</groupId>
            <artifactId>wxpay-sdk</artifactId>
            <version>0.0.3</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>

获取微信支付配置信息

#关联的公众号appid
weixin.pay.appid=关联的公众号appid
#商户号
weixin.pay.partner=你的商户号
#商户key
weixin.pay.partnerkey=你的商户key
#回调地址
weixin.pay.notifyurl=你的回调地址
#微信支付提供的固定地址
weixin.pay.url=微信支付提供的固定地址
#查询微信支付状态固定地址
weixin.pay.queryurl=查询微信支付状态固定地址

读取配置文件信息工具类

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class WeiXinPayPropertiesUtil implements InitializingBean {

    @Value("${weixin.pay.appid}")
    private String appId;

    @Value("${weixin.pay.partner}")
    private String partner;

    @Value("${weixin.pay.partnerkey}")
    private String partnerkey;

    @Value("${weixin.pay.notifyurl}")
    private String notifyurl;

    @Value("${weixin.pay.url}")
    private String url;

    @Value("${weixin.pay.queryurl}")
    private String queryurl;

    public static String WX_PAY_APP_ID;
    public static String WX_PAY_PARTNER;
    public static String WX_PAY_PARTNERKEY;
    public static String WX_PAY_NOTIFYURL;
    public static String WX_PAY_URL;
    public static String WX_PAY_QUERY_URL;

    @Override
    public void afterPropertiesSet() throws Exception {
        WX_PAY_APP_ID = appId;
        WX_PAY_PARTNER = partner;
        WX_PAY_PARTNERKEY = partnerkey;
        WX_PAY_NOTIFYURL = notifyurl;
        WX_PAY_URL = url;
        WX_PAY_QUERY_URL = queryurl;
    }
}

发起请求的工具类

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * http请求客户端
 * 
 * @author qy
 * 
 */
public class HttpClient {
	private String url;
	private Map<String, String> param;
	private int statusCode;
	private String content;
	private String xmlParam;
	private boolean isHttps;

	public boolean isHttps() {
		return isHttps;
	}

	public void setHttps(boolean isHttps) {
		this.isHttps = isHttps;
	}

	public String getXmlParam() {
		return xmlParam;
	}

	public void setXmlParam(String xmlParam) {
		this.xmlParam = xmlParam;
	}

	public HttpClient(String url, Map<String, String> param) {
		this.url = url;
		this.param = param;
	}

	public HttpClient(String url) {
		this.url = url;
	}

	public void setParameter(Map<String, String> map) {
		param = map;
	}

	public void addParameter(String key, String value) {
		if (param == null)
			param = new HashMap<String, String>();
		param.put(key, value);
	}

	public void post() throws ClientProtocolException, IOException {
		HttpPost http = new HttpPost(url);
		setEntity(http);
		execute(http);
	}

	public void put() throws ClientProtocolException, IOException {
		HttpPut http = new HttpPut(url);
		setEntity(http);
		execute(http);
	}

	public void get() throws ClientProtocolException, IOException {
		if (param != null) {
			StringBuilder url = new StringBuilder(this.url);
			boolean isFirst = true;
			for (String key : param.keySet()) {
				if (isFirst)
					url.append("?");
				else
					url.append("&");
				url.append(key).append("=").append(param.get(key));
			}
			this.url = url.toString();
		}
		HttpGet http = new HttpGet(url);
		execute(http);
	}

	/**
	 * set http post,put param
	 */
	private void setEntity(HttpEntityEnclosingRequestBase http) {
		if (param != null) {
			List<NameValuePair> nvps = new LinkedList<NameValuePair>();
			for (String key : param.keySet())
				nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数
			http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
		}
		if (xmlParam != null) {
			http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
		}
	}

	private void execute(HttpUriRequest http) throws ClientProtocolException,
			IOException {
		CloseableHttpClient httpClient = null;
		try {
			if (isHttps) {
				SSLContext sslContext = new SSLContextBuilder()
						.loadTrustMaterial(null, new TrustStrategy() {
							// 信任所有
							public boolean isTrusted(X509Certificate[] chain,
									String authType)
									throws CertificateException {
								return true;
							}
						}).build();
				SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
						sslContext);
				httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
						.build();
			} else {
				httpClient = HttpClients.createDefault();
			}
			CloseableHttpResponse response = httpClient.execute(http);
			try {
				if (response != null) {
					if (response.getStatusLine() != null)
						statusCode = response.getStatusLine().getStatusCode();
					HttpEntity entity = response.getEntity();
					// 响应内容
					content = EntityUtils.toString(entity, Consts.UTF_8);
				}
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpClient.close();
		}
	}

	public int getStatusCode() {
		return statusCode;
	}

	public String getContent() throws ParseException, IOException {
		return content;
	}

}

3.生成微信支付二维码

controller

@ApiOperation("生成支付二维码")
    @GetMapping("/createNative/{orderNo}")
    public R createNative(@PathVariable String orderNo) {
        Map map = payService.createNative(orderNo);
        log.info("生成支付二维码集合:{}",map);
        return R.ok().data(map);
    }

service

public Map createNative(String orderNo) {
        try {
            //1.根据订单id获取订单信息
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_no", orderNo);
            Order order = orderService.getOne(queryWrapper);

            //2.设置请求参数
            Map m = new HashMap();
            //关联的公众号appid
            m.put("appid", WeiXinPayPropertiesUtil.WX_PAY_APP_ID);
            //商户号
            m.put("mch_id", WeiXinPayPropertiesUtil.WX_PAY_PARTNER);
            //生产随机字符串让每个二维码都不一样
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            //生成二维码中要显示的标题
            m.put("body", order.getCourseTitle());
            //二维码唯一标识
            m.put("out_trade_no", orderNo);
            //二维码中的价格
            m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue() + "");
            //支付的ip地址(项目的域名)
            m.put("spbill_create_ip", "127.0.0.1");
            //支付之后的回调地址(这里没有用到)
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            //支付的类型(NATIVE-二维码)
            m.put("trade_type", "NATIVE");

            //3、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient(WeiXinPayPropertiesUtil.WX_PAY_URL);
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, WeiXinPayPropertiesUtil.WX_PAY_PARTNERKEY));
            //支持https
            client.setHttps(true);
            //发起请求
            client.post();

            //获取响应结果
            //响应结果为xml格式的字符串
            String xml = client.getContent();

            //微信提供了将xml转换为map的方法
            //返回的参数中包含了二维码地址code_url和result_code
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            Map map = new HashMap<>();
            //订单号
            map.put("out_trade_no", orderNo);
            //课程id
            map.put("course_id", order.getCourseId());
            //支付金额
            map.put("total_fee", order.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));
            //二维码地址
            map.put("code_url", resultMap.get("code_url"));

            //微信支付二维码2小时过期,可采取2小时未支付取消订单
            //redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
            return map;
        } catch (Exception e) {
            throw new GuliException(ResultCode.ERROR, "生成微信支付二维码失败");
        }
    }

4.查询微信支付状态

controller

@ApiOperation("查询订单支付状态")
    @GetMapping("/queryPayStatus/{orderNo}")
    public R queryPayStatus(@PathVariable String orderNo) {
        //调用查询接口
        Map<String, String> map = payService.queryPayStatus(orderNo);
        if (map == null) {//出错
            return R.error().message("支付出错");
        }
        //如果成功
        if (map.get("trade_state").equals("SUCCESS")) {
            //更改订单状态
            payService.updateOrderStatus(map);
            return R.ok().message("支付成功");
        }

        return R.ok().code(25000).message("支付中");
    }

service

//查询微信支付状态   
public Map<String, String> queryPayStatus(String orderNo) {
        try {
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", WeiXinPayPropertiesUtil.WX_PAY_APP_ID);
            m.put("mch_id", WeiXinPayPropertiesUtil.WX_PAY_PARTNER);
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            //查询微信支付状态,固定地址
            HttpClient client = new HttpClient(WeiXinPayPropertiesUtil.WX_PAY_QUERY_URL);
            client.setXmlParam(WXPayUtil.generateSignedXml(m, WeiXinPayPropertiesUtil.WX_PAY_PARTNERKEY));
            client.setHttps(true);
            client.post();

            //3、获取返回第三方的数据
            String xml = client.getContent();

            //4、转成Map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            //5、返回
            return resultMap;
        } catch (Exception e) {
            throw new GuliException(ResultCode.ERROR, "查询订单支付状态失败");
        }
}
	
//更改订单状态
public void updateOrderStatus(Map<String, String> map) {
        //1.获取订单id
        String orderNo = map.get("out_trade_no");

        //2.根据订单id查询订单信息
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        Order order = orderService.getOne(wrapper);

        //3.变更订单状态
        Integer status = order.getStatus();
        if(status == 1){
            return;
        }
        order.setStatus(1);
        orderService.updateById(order);

        //4.记录支付日志
        PayLog payLog=new PayLog();
        //支付订单号
        payLog.setOrderNo(order.getOrderNo());
        //支付时间
        payLog.setPayTime(new Date());
        //支付类型
        payLog.setPayType(1);
        //总金额(分)
        payLog.setTotalFee(order.getTotalFee());
        //支付状态
        payLog.setTradeState(map.get("trade_state"));
        //流水号
        payLog.setTransactionId(map.get("transaction_id"));
        //其他属性
        payLog.setAttr(JSONObject.toJSONString(map));
        //插入到支付日志表
        baseMapper.insert(payLog);
}

5.最终效果

image-20220130233051374


标题:微信扫码支付
作者:llp
地址:https://llinp.cn/articles/2022/01/30/1643556779232.html