sunshine
2024-11-05 53bd8a8d8184b3f19695b756ee78f343cdb9b9b9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/**
 * 
 */
/**
 * @author Administrator
 *
 */
package com.nova.sankuai.infra.utils.baofu;
 
import com.alibaba.fastjson.JSON;
import com.nova.sankuai.domain.entity.PayRecord;
import com.nova.sankuai.infra.config.CommonException;
import com.nova.sankuai.infra.utils.baofu.http.*;
import com.nova.sankuai.service.IPayRecordService;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
 
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
@Component
public class PayHttpUtil {
 
    private static final Logger log = LoggerFactory.getLogger("baofuLog");
    
    public String RequestForm(String Url,Map<String,String> Parms){
        if(Parms.isEmpty()){
            return  "参数不能为空!";
        }
        String PostParms = "";
        int PostItemTotal = Parms.keySet().size();
        int Itemp=0;
        for (String key : Parms.keySet()){
            PostParms += key + "="+Parms.get(key);
            Itemp++;
            if(Itemp<PostItemTotal){
                PostParms +="&";
            }
        }
        HttpSendModel httpSendModel = new HttpSendModel(Url + "?" + PostParms);
//        Log.Write("【请求全部参数】:" + Url + "?" + PostParms);
        String recordTypeStr = "";// 交易类型说明
        String recordType = "";// 交易类型
        if (Url.contains("/cutpayment/protocol/backTransRequest")) {
            String txnType = Parms.get("txn_type");// 交易类型
            if ("01".equals(txnType)) {
                recordTypeStr = "宝付支付预绑卡";
                recordType = "bp";
            } else if ("02".equals(txnType)) {
                recordTypeStr = "宝付支付确认绑卡";
                recordType = "bc";
            } else if ("05".equals(txnType)) {
                recordTypeStr = "宝付支付预支付";
                recordType = "bs";
            } else if ("06".equals(txnType)) {
                recordTypeStr = "宝付支付确认支付";
                recordType = "bf";
            }
        }
        log.info(recordTypeStr + "入参:{}", JSON.toJSONString(Parms));
        httpSendModel.setMethod(HttpMethod.POST);
        SimpleHttpResponse response = null;
        try {
            response = doRequest(httpSendModel, "utf-8");
            log.info(recordTypeStr + "返回结果:{}", response.getEntityString());
        } catch (Exception e) {
            String userId = Parms.get("user_id");
            if (userId != null) {
                PayRecord payRecord = new PayRecord();
                LocalDateTime payDate = LocalDateTime.now();
                payRecord.setPayDate(payDate);
                payRecord.setUserId(Long.parseLong(userId));
                payRecord.setPayType(recordType);
                payRecord.setPayStatus(3);
                payRecord.setPayError(e.getMessage());
                payRecord.setPayErrorCode("bf00001");
                payRecord.setOutTradeNo(Parms.get("msg_id"));
                payRecordImpl(payRecord);
            }
 
            log.error(recordTypeStr + "读取宝付服务器失败,请求全部参数:{}", Url + "?" + PostParms);
            throw new CommonException("服务器发生错误,错误码:bf00001");
        }
        return response.getEntityString();
 
    }
    
    public SimpleHttpResponse doRequest(HttpSendModel httpSendModel,
            String getCharSet) throws Exception {
 
        // 创建默认的httpClient客户端端
        SimpleHttpClient simpleHttpclient = new SimpleHttpClient();
 
        try {
            return doRequest(simpleHttpclient, httpSendModel, getCharSet);
        } finally {
            simpleHttpclient.getHttpclient().getConnectionManager().shutdown();
        }
 
    }
 
    /**
     * @param httpSendModel
     * @param getCharSet
     * @return
     * @throws Exception 
     */
    public SimpleHttpResponse doRequest(
            SimpleHttpClient simpleHttpclient, HttpSendModel httpSendModel,
            String getCharSet) throws Exception {
 
        HttpRequestBase httpRequest = buildHttpRequest(httpSendModel);
 
        if (httpSendModel.getUrl().startsWith("https://")) {
            simpleHttpclient.enableSSL();
        }
 
        try {
            HttpResponse response = simpleHttpclient.getHttpclient().execute(
                    httpRequest);
            int statusCode = response.getStatusLine().getStatusCode();
 
            if (isRequestSuccess(statusCode)) {
                return new SimpleHttpResponse(statusCode, EntityUtils.toString(
                        response.getEntity(), getCharSet), null);
            } else {
                return new SimpleHttpResponse(statusCode, null, response
                        .getStatusLine().getReasonPhrase());
            }
 
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("http请求异常", e);
        }
 
    }
 
    /**
     * @param httpSendModel
     * @return
     * @throws Exception 
     */
    protected HttpRequestBase buildHttpRequest(
            HttpSendModel httpSendModel) throws Exception {
        HttpRequestBase httpRequest;
        if (httpSendModel.getMethod() == null) {
            throw new Exception("请求方式未设定");
        } else if (httpSendModel.getMethod() == HttpMethod.POST) {
 
            String url = httpSendModel.getUrl();
            String sendCharSet = httpSendModel.getCharSet();
            List<HttpFormParameter> params = httpSendModel.getParams();
            List<NameValuePair> qparams = new ArrayList<NameValuePair>();
            if (params != null && params.size() != 0) {
 
                for (HttpFormParameter param : params) {
                    qparams.add(new BasicNameValuePair(param.getName(), param
                            .getValue()));
                }
 
            }
 
            HttpPost httppost = new HttpPost(url);
            try {
                httppost.setEntity(new UrlEncodedFormEntity(qparams,
                        sendCharSet));
            } catch (UnsupportedEncodingException e) {
                throw new Exception("构建post请求参数失败", e);
            }
 
            httpRequest = httppost;
        } else if (httpSendModel.getMethod() == HttpMethod.GET) {
            HttpGet httpget = new HttpGet(httpSendModel.buildGetRequestUrl());
 
            httpRequest = httpget;
        } else {
            throw new Exception("请求方式不支持:" + httpSendModel.getMethod());
        }
 
        return httpRequest;
    }
 
    /**
     * 请求是否成功
     * 
     * @param statusCode
     * @return
     */
    public static boolean isRequestSuccess(int statusCode) {
        return statusCode == 200;
    }
 
 
    @Resource
    private PlatformTransactionManager transactionManager;// 引入 (平台)事务管理器,Spring 事务策略的核心。
    // 于2022-11-17号
    @Resource
    private IPayRecordService payRecordService;
    /**
     * 于2022-11-18新增:录入支付记录表
     */
    @Async
    public void payRecordImpl(PayRecord payRecord) {
        // 发起一个新事务
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);//新发起一个事务
        TransactionStatus defStatus = transactionManager.getTransaction(def);// 获得事务状态
        payRecordService.save(payRecord);
        transactionManager.commit(defStatus);// 手动提交事务
    }
    
}