新版仿ok交易所-后端
zyy
2026-01-30 dab541253155333bd065c83f04c1dd9228b8a1d2
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package com.yami.trading.api.controller.exchange;
 
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yami.trading.bean.vo.RechargeAddressVo;
import com.yami.trading.common.constants.RedisKeys;
import com.yami.trading.huobi.hobi.http.HttpHelper;
import com.yami.trading.security.common.enums.CryptoCurrencyEnum;
import com.yami.trading.security.common.util.LocalKeyStorageAESUtil;
import com.yami.trading.api.UD.*;
import com.yami.trading.api.UD.Address;
import com.yami.trading.bean.exchange.PartyBlockchain;
import com.yami.trading.bean.model.ChannelBlockchain;
import com.yami.trading.bean.model.RechargeBlockchainOrder;
import com.yami.trading.bean.model.User;
import com.yami.trading.common.constants.Constants;
import com.yami.trading.common.domain.Result;
import com.yami.trading.common.exception.YamiShopBindException;
import com.yami.trading.common.util.MD5;
import com.yami.trading.common.util.StringUtils;
import com.yami.trading.security.common.util.SecurityUtils;
import com.yami.trading.service.ChannelBlockchainService;
import com.yami.trading.service.RechargeBlockchainOrderService;
import com.yami.trading.service.exchange.PartyBlockchainService;
import com.yami.trading.service.syspara.SysparaService;
import com.yami.trading.service.user.UserService;
import com.yami.trading.sys.model.SysUser;
import com.yami.trading.sys.service.SysUserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
 
@RestController
@Slf4j
@Api(tags = "区块链 -api")
public class ApiChannelBlockchainController {
    @Autowired
    private SysparaService sysparaService;
    private final String action = "/api/channelBlockchain!";
    @Autowired
    private ChannelBlockchainService channelBlockchainService;
    private OkHttpClient okHttpClient = new OkHttpClient();
    private final String threedUrl = "https://api.star-pay.vip/api/gateway/pay";
    @Autowired
    UserService userService;
    @Autowired
    PartyBlockchainService partyBlockchainService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    RechargeBlockchainOrderService rechargeBlockchainOrderService;
    @Autowired
    UdunClient udunClient;
 
    /**
     * 获取所有链地址
     */
    @RequestMapping(action + "list.action")
    public Object list() throws IOException {
        List<ChannelBlockchain> data = new ArrayList<ChannelBlockchain>();
        String partyId = SecurityUtils.getUser().getUserId();
        User party = userService.getById(partyId);
        List<PartyBlockchain> list = partyBlockchainService.findByUserName(party.getUserName());
        if (null != list && !list.isEmpty()) {
            data = list.stream().map(dict -> {
                String qrImage = dict.getQrImage();
                String chainAddress = dict.getAddress();
                String chainName = dict.getChainName();
                String coinSymbol = dict.getCoinSymbol();
                String autoStr = dict.getAuto();
                boolean auto = autoStr.equals("Y") ? true : false;
                ChannelBlockchain cbc = new ChannelBlockchain();
                cbc.setBlockchainName(chainName);
                cbc.setBlockchain_name(chainName);
                cbc.setAddress(chainAddress);
                cbc.setCoin(coinSymbol);
                cbc.setAuto(auto);
                cbc.setImg(qrImage);
                return cbc;
            }).collect(Collectors.toList());
        }
        if (data.isEmpty()) data = channelBlockchainService.list();
        for (int i = 0; i < data.size(); i++) {
            data.get(i).setBlockchain_name(data.get(i).getBlockchainName());
            if (1 == this.sysparaService.find("can_recharge").getInteger()) {
                // 允许在线充值,展示二维码
                if (!StringUtils.isNullOrEmpty(data.get(i).getImg())) {
                    String path = Constants.WEB_URL + "/public/showimg!showImg.action?imagePath=" + data.get(i).getImg();
                    data.get(i).setImg(path);
                }
            } else {
                data.get(i).setImg(null);
                data.get(i).setAddress(null);
            }
        }
        return Result.succeed(data);
    }
 
    /**
     * 根据币种获取链地址
     */
    /*@GetMapping(action + "getBlockchainName.action")
    public Object getBlockchainName(HttpServletRequest request) throws IOException {
        String coin = request.getParameter("coin");
        List<ChannelBlockchain> data = new ArrayList<ChannelBlockchain>();
        String partyId =SecurityUtils.getUser().getUserId();
        if(coin.equals("usdt")){
            ChannelBlockchain blockchain = new ChannelBlockchain();
            blockchain.setBlockchain_name("TRC20");
            blockchain.setAddress("TTVcevkA5s6ysCZkWhcLzMJg2ty5BDjpVV");
            blockchain.setCoin(coin);
            blockchain.setAuto(false);
            blockchain.setImg(null);
            data.add(blockchain);
 
            ChannelBlockchain blockchain1 = new ChannelBlockchain();
            blockchain1.setBlockchain_name("ERC20");
            blockchain1.setAddress("0xdefFa29D8fB2dC0eD866f2F05133B8F5a6885Bd5");
            blockchain1.setCoin(coin);
            blockchain1.setAuto(false);
            blockchain1.setImg(null);
            data.add(blockchain1);
        }else if(coin.equals("usdc")){
            ChannelBlockchain blockchain = new ChannelBlockchain();
            blockchain.setBlockchain_name("TRC20");
            blockchain.setAddress("TTVcevkA5s6ysCZkWhcLzMJg2ty5BDjpVV");
            blockchain.setCoin(coin);
            blockchain.setAuto(false);
            blockchain.setImg(null);
            data.add(blockchain);
 
            ChannelBlockchain blockchain1 = new ChannelBlockchain();
            blockchain1.setBlockchain_name("ERC20");
            blockchain1.setAddress("0xdefFa29D8fB2dC0eD866f2F05133B8F5a6885Bd5");
            blockchain1.setCoin(coin);
            blockchain1.setAuto(false);
            blockchain1.setImg(null);
            data.add(blockchain1);
        }else  if(coin.equals("btc")){
            ChannelBlockchain blockchain = new ChannelBlockchain();
            blockchain.setBlockchain_name("BTC");
            blockchain.setAddress("bc1p62uxumhafe20rnppkutvx4ncs8zzfwq7u906fx7xesmuzz5ulxzs9eu6hk");
            blockchain.setCoin(coin);
            blockchain.setAuto(false);
            blockchain.setImg(null);
            data.add(blockchain);
        }else if(coin.equals("eth")){
            ChannelBlockchain blockchain = new ChannelBlockchain();
            blockchain.setBlockchain_name("ETH");
            blockchain.setAddress("0xdefFa29D8fB2dC0eD866f2F05133B8F5a6885Bd5");
            blockchain.setCoin(coin);
            blockchain.setAuto(false);
            blockchain.setImg(null);
            data.add(blockchain);
        }
 
        return Result.succeed(data);
    }*/
 
    /**
     * 根据币种获取链地址
     */
    @GetMapping(action + "getBlockchainName.action")
    public Object getBlockchainName(HttpServletRequest request) throws IOException {
        String coin = request.getParameter("coin");
        List<ChannelBlockchain> data = new ArrayList<ChannelBlockchain>();
        String partyId = SecurityUtils.getUser().getUserId();
        User party = userService.getById(partyId);
        if (0 == this.sysparaService.find("can_recharge").getInteger()) {
            return Result.failed("请联系客服充值");
        }
        List<PartyBlockchain> list = partyBlockchainService.findByUserNameAndCoinSymbol(party.getUserName(), coin);
        if (null != list && !list.isEmpty()) {
            data = list.stream().map(dict -> {
                String qrImage = dict.getQrImage();
                String chainAddress = dict.getAddress();
                String chainName = dict.getChainName();
                String coinSymbol = dict.getCoinSymbol();
                String autoStr = dict.getAuto();
                boolean auto = autoStr.equals("Y") ? true : false;
                ChannelBlockchain cbc = new ChannelBlockchain();
                cbc.setBlockchain_name(chainName);
                cbc.setAddress(chainAddress);
                cbc.setCoin(coinSymbol);
                cbc.setAuto(auto);
                cbc.setImg(qrImage);
                return cbc;
            }).collect(Collectors.toList());
        }
        if (data.isEmpty()) data = this.channelBlockchainService.findByCoin(coin.toLowerCase());
        for (int i = 0; i < data.size(); i++) {
            data.get(i).setBlockchain_name(data.get(i).getBlockchainName());
            if (1 == this.sysparaService.find("can_recharge").getInteger()) {
                if (!StringUtils.isNullOrEmpty(data.get(i).getImg())) {
                    QrConfig config = new QrConfig(150, 150);
                    config.setMargin(3);
                    String qr = QrCodeUtil.generateAsBase64(data.get(i).getAddress(), config, "png");
                    data.get(i).setImgStr(qr);
//                    data.get(i).setImgStr("/public/showimg!showImg.action?imagePath=" + data.get(i).getImg());
//                    data.get(i).setImg(path);
                }
            } else {
                data.get(i).setImg(null);
                data.get(i).setImgStr(null);
                data.get(i).setAddress(null);
            }
        }
        return Result.succeed(data);
    }
 
    @PostMapping(action +"rechargeCallback.action")
    public ResultMsg rechargeCallback(HttpServletRequest request){
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String sign = request.getParameter("sign");
        String body = request.getParameter("body");
 
        ResultMsg resultMsg = new ResultMsg();
        try{
            log.info("===rechargeCallback===:{}", body);
            boolean flag = udunClient.checkSign(timestamp, nonce, body, sign);
            log.info("===rechargeCallback===sign:{}", flag);
 
            if (!flag){
                resultMsg.setCode(406);
                resultMsg.setMessage("充值回调验签失败");
                return resultMsg;
            }
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(body, HashMap.class);
            double amounts = Double.parseDouble(map.get("amount").toString());  // 假设 amount 的值为 1000
            double decimals = Double.parseDouble(map.get("decimals").toString());
            double success_amount  = amounts / Math.pow(10, decimals);
            String address = map.get("address").toString();
 
            RechargeBlockchainOrder blockchainOrder = rechargeBlockchainOrderService.getOne(new LambdaQueryWrapper<>(RechargeBlockchainOrder.class)
                    .eq(RechargeBlockchainOrder::getSucceeded, 0)
                    .eq(RechargeBlockchainOrder::getChannelAddress, address).last(" limit 1 "));
            if(ObjectUtil.isEmpty(blockchainOrder)){
                resultMsg.setCode(200);
                return resultMsg;
            }
            Integer status = Integer.valueOf(map.get("status").toString());
            User user = userService.getById(blockchainOrder.getPartyId());
 
            log.info("===rechargeCallback==d=blockchainOrder:{}", blockchainOrder);
            if (status == 3) { //交易成功
                rechargeBlockchainOrderService.manualReceipt(1,blockchainOrder.getOrderNo(), BigDecimal.valueOf(success_amount),user.getUserName());
            } else if(status == 2) {   //驳回
                rechargeBlockchainOrderService.refusalApply(blockchainOrder.getUuid(), "订单失败:" + status, user.getUserName());
            }
 
            resultMsg.setCode(200);
            return resultMsg;
        }catch (Exception e){
            resultMsg.setCode(500);
            resultMsg.setMessage("回调处理失败");
            return resultMsg;
        }
    }
 
    /**
     * 根据第三方充值链接
     */
    @RequestMapping(action + "getThirdUrl.action")
    public Result getThirdUrl(HttpServletRequest request) throws IOException {
 
        String key = this.sysparaService.find("third_key").getSvalue();
        String merchant_no = this.sysparaService.find("third_id").getSvalue();
        int i = (int) (Math.random() * 900) + 100;
        //商户号
        //10位时间戳
        String timestamp = "" + System.currentTimeMillis() / 1000;
        String amount = request.getParameter("amount");
        //法币名称
        String fiat_currency = request.getParameter("fiat_currency");
        //订单号
        String merchant_ref = System.currentTimeMillis() + "" + i;
        //产品名称
        String product = "ERC20Buy";
        String sign_type = "MD5";
        Map<String, String> requestparam = new HashMap<>();
        JSONObject params = new JSONObject(new LinkedHashMap<>());
        JSONObject extra = new JSONObject(new LinkedHashMap<>());
        extra.put("fiat_currency", fiat_currency);
        params.put("merchant_ref", merchant_ref);
        params.put("product", product);
        params.put("amount", amount);
        params.put("extra", extra);
        String waitsign = merchant_no + params + sign_type + timestamp + key;
        String sign = MD5.sign(waitsign);
        requestparam.put("merchant_no", merchant_no);
        requestparam.put("params", params.toJSONString());
        requestparam.put("sign", sign);
        requestparam.put("sign_type", sign_type);
        requestparam.put("timestamp", params.toJSONString());
        String result = "";
        RequestBody body = new FormBody.Builder()
                .add("merchant_no", merchant_no)
                .add("timestamp", timestamp)
                .add("sign_type", sign_type)
                .add("params", params.toString())
                .add("sign", sign)
                .build();
        Request requestParm = new Request.Builder()
                .url(threedUrl)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        try {
            Response response = okHttpClient.newCall(requestParm).execute();
            result = response.body().string();
        } catch (Exception e) {
           throw  new YamiShopBindException("请求第三方失败");
        }
        JSONObject resultJson = JSON.parseObject(result);
        Integer code = resultJson.getInteger("code");
        if (code == 200) {
            JSONObject resultParams = resultJson.getJSONObject("params");
            return Result.succeed(resultParams.getString("payurl"));
        } else {
            return Result.failed(resultJson.getString("message"));
 
        }
    }
}