Administrator
2024-02-26 b5b296cc01699f96029b07073fe9d0078bedd445
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package com.dy.pipirrWebChat.payment;
 
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.dy.common.aop.SsoAop;
import com.dy.common.webUtil.BaseResponse;
import com.dy.common.webUtil.BaseResponseUtils;
import com.dy.common.webUtil.ResultCodeMsg;
import com.dy.pipIrrGlobal.pojoSe.SeWebchatLogonState;
import com.dy.pipirrWebChat.util.OkHttpUtil;
import com.dy.pipirrWebChat.util.RestTemplateUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
 
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
/**
 * @author ZhuBaoMin
 * @date 2024-02-22 15:24
 * @LastEditTime 2024-02-22 15:24
 * @Description
 */
 
@Slf4j
@Tag(name = "微信支付管理", description = "微信支付各种操作")
@RestController
@RequestMapping(path="payment")
@RequiredArgsConstructor
public class PaymentCtrl {
    private final PaymentSv paymentSv;
    private final RestTemplateUtil restTemplateUtil;
    private String certFileName = PayInfo.certFileName;
 
    /**
     * 登录凭证校验
     * @param appid 小程序 appId
     * @param secret 小程序 appSecret
     * @param js_code 临时登录凭证code
     * @return
     * @throws Exception
     */
    @Operation(summary = "登录凭证校验", description = "登录凭证校验")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "操作结果:true:成功,false:失败(BaseResponse.content)",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Boolean.class))}
            )
    })
    @PostMapping(path = "getSessionId")
    @Transactional(rollbackFor = Exception.class)
    @SsoAop()
    public BaseResponse<Boolean> getSessionId(@RequestParam("appid")  String appid, @RequestParam("secret") String secret, @RequestParam("js_code") String js_code) throws Exception {
        String result = OkHttpUtil.builder().url("https://api.weixin.qq.com/sns/jscode2session")
                .addParam("appid", appid)
                .addParam("secret", secret)
                .addParam("js_code", js_code)
                .initGet()
                .sync();
        JSONObject job = JSONObject.parseObject(result);
        System.out.println(job.getString("session_key"));
 
        if(job.getLong("errcode") != null && job.getLong("errcode") >= -1) {
            return BaseResponseUtils.buildFail("登录凭证校验失败");
        }
 
        // 添加登录态记录
        SeWebchatLogonState po = new SeWebchatLogonState();
        po.setOpenId(job.getString("openid"));
        po.setSessionKey(job.getString("session_key"));
        Date createTime = new Date();
        po.setCreateTime(createTime);
        Long id = paymentSv.insert(po);
        if(id == null || id <= 0) {
            return BaseResponseUtils.buildFail("登录态记录添加失败");
        }
 
        String SessionId = String.valueOf(id);
        return BaseResponseUtils.buildSuccess(SessionId) ;
    }
 
    @Operation(summary = "下载平台证书", description = "下载平台证书")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "操作结果:true:成功,false:失败(BaseResponse.content)",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Boolean.class))}
            )
    })
    @GetMapping(path = "certificates")
    @Transactional(rollbackFor = Exception.class)
    @SsoAop()
    public BaseResponse<JSONObject> certificates() throws Exception {
        //String prepayId = "";
        //SeWebchatLogonState po = paymentSv.selectOne(Long.parseLong(sessionId));
        //String openid = po.getOpenId();
 
        String method = "GET";
        String httpUrl = "/v3/certificates";
        String nonceStr = PayHelper.generateRandomString();
        Long timestamp = System.currentTimeMillis() / 1000;
 
        String header = PayInfo.schema + " " + PayHelper.getToken(method, httpUrl, "", nonceStr, timestamp, certFileName);
 
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", header);
        headers.put("Accept", "application/json");
        JSONObject job_result = restTemplateUtil.get(PayInfo.certificates,null, headers);
        if(job_result != null) {
            JSONArray array = job_result.getJSONArray("data");
            if(array != null && array.size() > 0) {
                for(int i = 0; i < array.size(); i++) {
                    JSONObject job_data = array.getJSONObject(i);
                    String serial_no = job_data.getString("serial_no");
                    String effective_time  = job_data.getString("effective_time");
                    String expire_time  = job_data.getString("expire_time");
                    JSONObject job_certificate = job_data.getJSONObject("encrypt_certificate");
                    String algorithm = job_certificate.getString("algorithm");
                    String nonce  = job_certificate.getString("nonce");
                    String associated_data  = job_certificate.getString("associated_data");
                    String ciphertext  = job_certificate.getString("ciphertext");
                }
            }
        }
        System.out.println(job_result.toJSONString());
        return BaseResponseUtils.buildSuccess(job_result.toJSONString()) ;
    }
 
    /**
     * JSAPI下单
     * @param sessionId
     * @param orderNumber
     * @param payAmount
     * @return
     * @throws Exception
     */
    @Operation(summary = "统一下单", description = "统一下单")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "操作结果:true:成功,false:失败(BaseResponse.content)",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Boolean.class))}
            )
    })
    @PostMapping(path = "unifiedOrder")
    @Transactional(rollbackFor = Exception.class)
    @SsoAop()
    public BaseResponse<Boolean> unifiedOrder(@RequestParam("sessionId")  String sessionId, @RequestParam("orderNumber") String orderNumber, @RequestParam("payAmount") String payAmount) throws Exception {
        String prepayId = "";
        SeWebchatLogonState po = paymentSv.selectOne(Long.parseLong(sessionId));
        String openid = po.getOpenId();
 
        JSONObject job_body = new JSONObject();
        job_body.put("appid", PayInfo.appid);
        job_body.put("mchid", PayInfo.mchid);
        job_body.put("description", PayInfo.description);
        job_body.put("out_trade_no", orderNumber);
        job_body.put("notify_url", PayInfo.notifyUrl);
 
        //订单金额
        JSONObject job_amount = new JSONObject();
        job_amount.put("total", 1);
        job_amount.put("currency", "CNY");
        job_body.put("amount", job_amount);
 
        //支付者
        JSONObject job_payer = new JSONObject();
        job_payer.put("openid", openid);
        job_body.put("payer", job_payer);
 
        // 获取随机串和时间戳,放在此处以保证
        String nonceStr = PayHelper.generateRandomString();
        Long timestamp = System.currentTimeMillis() / 1000;
 
        String method = "POST";
        String httpUrl = "/v3/pay/transactions/jsapi";
 
        String body = job_body.toJSONString();
        String header = PayInfo.schema + " " + PayHelper.getToken(method, httpUrl, body, nonceStr, timestamp, certFileName);
 
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", header);
        headers.put("Accept", "application/json");
        headers.put("Content-Type", "application/json");
 
        JSONObject job_result = restTemplateUtil.post(PayInfo.orderUrl, body, headers);
        if(job_result != null) {
            System.out.println(job_result.toString());
            prepayId = job_result.getString("prepay_id");
        }
 
 
 
        //String result = OkHttpUtil.builder().url(PayInfo.orderUrl)
        //        .addBody(body)
        //        .addHeader("Authorization", header)
        //        .addHeader("Accept", "application/json")
        //        .addHeader("Content-Type", "application/json")
        //        .initPost(true)
        //        .sync();
        //System.out.println(result);
 
        return BaseResponseUtils.buildSuccess(prepayId) ;
    }
 
    /**
     * 再次签名
     * @param prepayId 预支付交易会话标识
     * @return 小程序调起支付参数
     * @throws Exception
     */
    @Operation(summary = "再次签名", description = "再次签名")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = ResultCodeMsg.RsCode.SUCCESS_CODE,
                    description = "操作结果:true:成功,false:失败(BaseResponse.content)",
                    content = {@Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = Boolean.class))}
            )
    })
    @GetMapping(path = "/signAgain")
    @Transactional(rollbackFor = Exception.class)
    @SsoAop()
    public BaseResponse<JSONObject> signAgain(@RequestParam("prepayId")  String prepayId) throws Exception {
 
        // 获取随机串和时间戳,放在此处以保证
        String appid = PayInfo.appid;
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonceStr = PayHelper.generateRandomString();
        String pkg = "prepay_id=" + prepayId;
        String signType = PayInfo.signType;
        String message = PayHelper.buildMessage_signAgain(appid, timestamp, nonceStr, pkg);
        String paySign = PayHelper.sign(message.getBytes("utf-8"), certFileName);
 
        JSONObject job_result = new JSONObject();
        job_result.put("timestamp", timestamp);
        job_result.put("nonceStr", nonceStr);
        job_result.put("package", pkg);
        job_result.put("signType", signType);
        job_result.put("paySign", paySign);
 
        return BaseResponseUtils.buildSuccess(job_result) ;
    }
}