课程支付(生成微信支付二维码接口)

1、在service_order模块编写controller,返回一个map集合

java 复制代码
@Api(description="支付管理")
@RestController
@RequestMapping("/orderservice/paylog")
@CrossOrigin
public class TPayLogController { 
    @Autowired
    private TPayLogService payLogService;

    @ApiOperation(value = "根据订单号生成支付二维码")
    @GetMapping("createNative/{orderNo}")
    public R createNative(@PathVariable String orderNo){
        Map<String,Object>  map = payLogService.createNative(orderNo);
        return R.ok().data(map);
    }

}

2、编写service

(1)引入工具类

java 复制代码
package com.atguigu.orderservice.utils;
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;
   }

}

(2)com/atguigu/orderservice/service/TPayLogService添加接口方法

java 复制代码
Map<String, Object> createNative(String orderNo);

(3)com/atguigu/orderservice/service/impl/TPayLogServiceImpl实现接口方法

java 复制代码
@Autowired
private TOrderService orderService;
//根据订单号生成支付二维码
@Override
public Map<String, Object> createNative(String orderNo) {

    try {
        //1根据订单号获取订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        TOrder order = orderService.getOne(wrapper);
        if(order==null){
            throw new GuliException(20001,"订单失效");
        }
        //2封装参数,用map
        Map m = new HashMap();
        //1、设置支付参数
        m.put("appid", "wx74862e0dfcf69954");//微信支付id
        m.put("mch_id", "1558950191");//商户号
        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()+"");//支付金额
        m.put("spbill_create_ip", "127.0.0.1");//终端ip地址
        m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");//支付回调地址
        m.put("trade_type", "NATIVE");//交易类型

        //3创建httpClient对象
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        //4向httpClient设置xml格式参数
        client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
        client.setHttps(true);
        client.post();
        //5发送请求得到返回结果
        String content = client.getContent();//xml格式
        System.out.println("content="+content);
        Map<String, String> map = WXPayUtil.xmlToMap(content);

        //6获取需要的值,进行封装,map
        Map<String, Object>resultMap = new HashMap<>();
        resultMap.put("out_trade_no", orderNo);
        resultMap.put("course_id", order.getCourseId());
        resultMap.put("total_fee", order.getTotalFee());
        resultMap.put("result_code", map.get("result_code"));
        resultMap.put("code_url", map.get("code_url"));

        return resultMap;
    } catch (Exception e) {
        throw new GuliException(20001,"生成支付二维码失败");
    }
}

3、测试

相关推荐
Bald Baby7 分钟前
JWT的使用
java·笔记·学习·servlet
魔道不误砍柴功13 分钟前
实际开发中的协变与逆变案例:数据处理流水线
java·开发语言
Rverdoser33 分钟前
RabbitMQ的基本概念和入门
开发语言·后端·ruby
dj244294570736 分钟前
JAVA中的Lamda表达式
java·开发语言
工业3D_大熊1 小时前
3D可视化引擎HOOPS Luminate场景图详解:形状的创建、销毁与管理
java·c++·3d·docker·c#·制造·数据可视化
szc17671 小时前
docker 相关命令
java·docker·jenkins
程序媛-徐师姐1 小时前
Java 基于SpringBoot+vue框架的老年医疗保健网站
java·vue.js·spring boot·老年医疗保健·老年 医疗保健
yngsqq1 小时前
c#使用高版本8.0步骤
java·前端·c#
尘浮生1 小时前
Java项目实战II基于微信小程序的校运会管理系统(开发文档+数据库+源码)
java·开发语言·数据库·微信小程序·小程序·maven·intellij-idea