• 准备工作
    • 概述:微信扫码支付是商户系统按微信支付协议生成支付二维码,用户再用微信扫一扫完成支付的模式。该模式适用于PC网站支付、实体店单品或订单支付、媒体广告支付等场景。
    • 第一步:注册公众号(类型须为:服务号):请根据营业执照类型选择以下主体注册:个体工商户| 企业/公司| 政府| 媒体| 其他类型。
    • 第二步:认证公众号:公众号认证后才可申请微信支付,认证费:300元/年。
    • 第三步:提交资料申请微信支付:登录公众平台,点击左侧菜单【微信支付】,开始填写资料等待审核,审核时间为1-5个工作日内。
    • 第四步:登录商户平台进行验证:资料审核通过后,请登录联系人邮箱查收商户号和密码,并登录商户平台填写财付通备付金打的小额资金数额,完成账户验证。
    • 第五步:在线签署协议:本协议为线上电子协议,签署后方可进行交易及资金结算,签署完立即生效。
  • 前期工作完成会下发重要信息
    • appid: 微信公众账号或开放平台APP的唯一标识
    • mch_id: 商户号,稍后用配置文件中的partner代替,见名知意
    • partnerkey: 商户密钥
    • sign: 数字签名,根据微信官方提供的密钥和一套算法生成的一个加密信息,就是为了保证交易的安全性
  • 在支付过程中,主要会用到微信支付SDK的以下功能
    • 获取随机字符串: WXPayUtil.generateNonceStr()
    • Map类型转换为xml字符串(自动添加签名): WXPayUtil.generateSignedXml(map, partnerkey)
    • xml字符串转换为Map类型: WXPayUtil.xmlToMap(result)
  • 在支付模块中导入微信支付依赖
<dependencies>
  <dependency>
    <groupId>com.github.wxpay</groupId>
    <artifactId>wxpay-sdk</artifactId>
    <version>0.0.3</version>
  </dependency>
</dependencies>
  • 配置文件添加微信支付信息,为了设置预付单的有效时间,还需要添加redis缓存信息
spring.redis.host=your_ip
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000
spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0

#关联的公众号appid
wx.appid=your_app_id
#商户号
wx.partner=your_partner
#商户key
wx.partnerkey=your_partner_key
  • 编写常量类读取配置文件中微信支付信息
@Component
public class WxPayProperties implements InitializingBean {
  @Value("${wx.appid}")
  private String appId;
  @Value("${wx.partner}")
  private String partner;
  @Value("${wx.partnerkey}")
  private String partnerKey;

  public static String WX_APP_ID;
  public static String WX_PARTNER;
  public static String WX_PARTNER_KEY;

  @Override
  public void afterPropertiesSet() throws Exception {
    WX_APP_ID = appId;
    WX_PARTNER = partner;
    WX_PARTNER_KEY = partnerKey;
  }
}
  • 借用HttpClient工具类,内容基本不用改,可尝试优化下
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.TrustSelfSignedStrategy;
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.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
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请求客户端 */
public class HttpClient {

    private String url;
    private Map<String, String> param;
    private int statusCode;
    private String content;
    private String xmlParam;
    private boolean isHttps;
    private boolean isCert = false;
    //证书密码 微信商户号(mch_id)
    private String certPassword;
    
    public HttpClient(String url, Map<String, String> param) {
        this.url = url;
        this.param = param;
    }

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

    public void addParameter(String key, String value) {
        if (param == null) param = new HashMap<>();
        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 completeUrl = new StringBuilder(this.url);
            boolean isFirst = true;
            for(Map.Entry<String, String> entry: param.entrySet()) {
                if(isFirst)  completeUrl.append("?");
                else completeUrl.append("&");
                completeUrl.append(entry.getKey()).append("=").append(entry.getValue());
                isFirst = false;
            }
            // 拼接成完整的url
            this.url = completeUrl.toString();
        }
        HttpGet http = new HttpGet(url);
        execute(http);
    }

    /** 设置post和put参数 */
    private void setEntity(HttpEntityEnclosingRequestBase http) {
        if (param != null) {
            List<NameValuePair> nvps = new LinkedList<>();
            for(Map.Entry<String, String> entry: param.entrySet())
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));   // 参数
            http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
        }
        if (!StringUtils.isEmpty(xmlParam)) http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
    }
    
    /** 执行get、post、put请求 */
    private void execute(HttpUriRequest http) throws ClientProtocolException, IOException {
        CloseableHttpClient httpClient = null;
        try {
            if (isHttps) {
                if(isCert) {
                    FileInputStream inputStream = new FileInputStream(WxPayProperties.CERT);
                    KeyStore keystore = KeyStore.getInstance("PKCS12");
                    char[] partnerId2charArray = certPassword.toCharArray();
                    keystore.load(inputStream, partnerId2charArray);
                    SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keystore, partnerId2charArray).build();
                    SSLConnectionSocketFactory sslsf =
                            new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
                                    null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
                    httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
                } else {
                    TrustSelfSignedStrategy strategy = new TrustSelfSignedStrategy() {
                        @Override
                        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                            // 信任所有
                            return true;
                        }
                    };
                    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, strategy).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 {
                assert response != null;
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert httpClient != null;
            httpClient.close();
        }
    }
    
    
    public int getStatusCode() {
        return statusCode;
    }
    
    public String getContent() throws ParseException, IOException {
        return content;
    }

    public boolean isHttps() {
        return isHttps;
    }

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

    public boolean isCert() {
        return isCert;
    }

    public void setCert(boolean cert) {
        isCert = cert;
    }

    public String getXmlParam() {
        return xmlParam;
    }

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

    public void setCertPassword(String certPassword) {
        this.certPassword = certPassword;
    }

    public void setParameter(Map<String, String> map) {
        param = map;
    }
}
  • 用户微信支付(前后端工作)
    • 后端生成微信支付二维码业务逻辑代码
@Service
public class WxPayServiceImpl implements WxPayService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /** 生成微信支付二维码 */
    @Override
    public Map<String, Object> createNative(String orderId) {
        try {
            // 如果缓存中有,就直接返回
            Map<String, Object> payMap = (Map<String, Object>) redisTemplate.opsForValue().get(orderId);
            if(payMap != null) return payMap;
            // 根据实际的业务需求编写相应的代码
            // 省略业务代码.......
            // 设置参数,
            // 把参数转换xml格式,使用商户key进行加密
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", WxPayProperties.WX_APP_ID);
            paramMap.put("mch_id", WxPayProperties.WX_PARTNER);
            // 随机字符串
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            String body = "请求体,应该是扫码支付时的文本信息";
            paramMap.put("body", body);
            // 实际开发中还是要保存当前字段到数据表中,供其他需求(如退款)使用
            paramMap.put("out_trade_no", "交易流水号,自定义即可,保证唯一性");
            paramMap.put("total_fee", "1"); // 支付的费用
            // 当前支付的IP地址
            paramMap.put("spbill_create_ip", "可以通过HttpServletRequest对象获取请求的IP地址");
            // 微信支付的回调地址
            paramMap.put("notify_url", "申请微信支付时填的回调地址");
            // 微信扫码支付
            paramMap.put("trade_type", "NATIVE");
            //4 调用微信生成二维码接口,httpclient调用,请求地址一般固定
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置xml参数(Map类型转换为xml)
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, WxPayProperties.WX_PARTNER_KEY));
            // 是https协议
            client.setHttps(true);
            client.post();
            //5 返回相关数据
            String xml = client.getContent();
            // xml数据转换为Map类型
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //6 封装返回结果集
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            // 状态码
            map.put("resultCode", resultMap.get("result_code"));
            //二维码地址
            map.put("codeUrl", resultMap.get("code_url"));

            if(resultMap.get("result_code") != null) {
                // 保存到Redis缓存中
                redisTemplateString.opsForValue().set(orderId.toString(),map,120, TimeUnit.MINUTES);
            }
            return map;
        }catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }
}
  • 前端引入vue-qriously生成二维码
    • 安装vue-qriously: npm install vue-qriously
    • 在插件文件中导入
    import VueQriously from 'vue-qriously'
    Vue.use(VueQriously)
    
    • vue组件显示二维码,只展示二维码区域
<!-- 微信支付弹出框 -->
<el-dialog :visible.sync="dialogPayVisible" style="text-align: left" :append-to-body="true" width="500px" @close="closeDialog">
  <div class="container">
    <div class="operate-view" style="height: 350px;">
      <div class="wrapper wechat">
        <div>
          <qriously :value="payObj.codeUrl" :size="220"/>
          <div style="text-align: center;line-height: 25px;margin-bottom: 40px;">
             请使用微信扫一扫<br/>
             扫描二维码支付
          </div>
        </div>
      </div>
    </div>
  </div>
</el-dialog>
<script>
import orderInfoApi from '@/api/order/orderInfo'
import weixinApi from '@/api/order/weixin'
export default {
  data() {
    return {
      orderId: null,
      orderInfo: {
        param: {}
      },

      dialogPayVisible: false,
      payObj: {},
      timer: null  // 定时器名称
    }
  },

  created() {
    this.orderId = this.$route.query.orderId
    this.init()
  },

  methods: {
    init() {
      orderInfoApi.getOrderInfo(this.orderId).then(response => {
        this.orderInfo = response.data
      })
    },
    pay() {
      this.dialogPayVisible = true

      weixinApi.createNative(this.orderId).then(response => {
        this.payObj = response.data
        if(this.payObj.codeUrl == '') {
          this.dialogPayVisible = false
          this.$message.error("支付错误")
        } else {
          this.timer = setInterval(() => {
            // 查看微信支付状态
            this.queryPayStatus(this.orderId)
          }, 3000);
        }
      })
    },

    queryPayStatus(orderId) {
      weixinApi.queryPayStatus(orderId).then(response => {
        if (response.message == '支付中') {
          return
        }
        clearInterval(this.timer);
        window.location.reload()
      })
    },
  }
}
</script>
  • 后端编写微信支付状态接口,同样省略支付成功之后的业务需求代码
@Service
public class WxPayServiceImpl implements WxPayService {
/** 查询支付状态 */
    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            // 封装提交参数
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", WxPayProperties.WX_APP_ID);
            paramMap.put("mch_id", WxPayProperties.WX_PARTNER);
            // 实际开发中还是要保存当前字段到数据表中,供其他需求(如退款)使用
            paramMap.put("out_trade_no", "当前支付订单的流水号");
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

            // 设置请求内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, WxPayProperties.WX_PARTNER_KEY));
            client.setHttps(true);
            client.post();

            // 得到微信接口返回数据
            String xml = client.getContent();
            // 其中返回的数据中会有transaction_id字段的数据,这是交易流水号,供退款使用
            return WXPayUtil.xmlToMap(xml);
        }catch(Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }
}
  • 注意支付(成功)之后返回的数据结果
  • 用户申请退款
    • 参考文档 下载证书
    • 在原有的配置文件中添加配置证书的路径(全路径)
wx.cert=absolute_path\\apiclient_cert.p12
  • 退款操作是根据支付记录发起的,所以支付和退款的交易单号必须保持一致
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private WxPayService wxPayService;
    @Override
    public boolean cancelOrder(Long orderId) {
        // 退款成功前关于订单、库存等其他业务的需求,需要根据实际开发场景编写,这里暂时忽略不写
        // ..........
        // 判断当前的订单是否可以取消
        if(OrderStatusEnum.PAID.getStatus().equals(orderInfo.getOrderStatus())) {
            // 调用退款方法
            boolean isRefund = wxPayService.refund(orderId);
            if(!isRefund) throw new YyghException(ResultCodeEnum.CANCEL_ORDER_FAIL);
            // 退款成功后业务需求代码省略不写
            // .........
        }
        return false;
    }
}
  • 主要的退款业务逻辑代码
@Service
public class WxPayServiceImpl implements WxPayService {
    /** 微信退款 */
    @Override
    public boolean refund(Long orderId) {
        try {
            // 其他业务代码需求,省略不写
            // ......
            
            // 封装map参数
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", WxPayProperties.WX_APP_ID);
            paramMap.put("mch_id", WxPayProperties.WX_PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            // 交易流水号(和支付成功之后的交易流水号保持一致)
            paramMap.put("transaction_id", paymentInfo.getTradeNo());
            // 商户订单号(和支付成功之后的交易流水号保持一致)
            paramMap.put("out_trade_no", paymentInfo.getOutTradeNo());
            // 商户退款单号
            paramMap.put("out_refund_no", "tk" + paymentInfo.getOutTradeNo());
            paramMap.put("total_fee", "1");
            paramMap.put("refund_fee", "1");
            // map类型数据转换为xml格式数据
            String paramXml = WXPayUtil.generateSignedXml(paramMap, WxPayProperties.WX_PARTNER_KEY);
            // 调用微信退款接口地址
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            // 设置xml参数
            client.setXmlParam(paramXml);
            client.setHttps(true);
            // 设置退款证书信息
            client.setCert(true);
            client.setCertPassword(WxPayProperties.WX_PARTNER);
            client.post();
            
            // 返回结果数据(xml格式)
            String xml = client.getContent();
            // xml格式数据转换为map类型数据
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            // 根据返回的退款结果做其他部分的需求,省略不写
            // ......
            return true;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}