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

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

@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)引入工具类

在这里插入图片描述

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添加接口方法

Map<String, Object> createNative(String orderNo);

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

@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、测试

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DKPT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值