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 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 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 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 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 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 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) ; } }