From cd409881a1fc1fc791f18f172b0ef8ebc1c21301 Mon Sep 17 00:00:00 2001 From: CodingCattwo <847701726@qq.com> Date: Tue, 29 Aug 2023 09:49:36 +0800 Subject: [PATCH 1/6] recover tool api --- .../webase/front/tool/ToolController.java | 464 +++++++++--------- .../front/tool/entity/ReqDecodeParam.java | 2 + .../front/tool/entity/ReqPrivateKey.java | 3 + .../webase/front/tool/entity/ReqSign.java | 3 + 4 files changed, 247 insertions(+), 225 deletions(-) diff --git a/src/main/java/com/webank/webase/front/tool/ToolController.java b/src/main/java/com/webank/webase/front/tool/ToolController.java index 9dfb3c3d5..c4e6213d9 100644 --- a/src/main/java/com/webank/webase/front/tool/ToolController.java +++ b/src/main/java/com/webank/webase/front/tool/ToolController.java @@ -1,225 +1,239 @@ -///** -// * Copyright 2014-2020 the original author or authors. -// *

-// * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except -// * in compliance with the License. You may obtain a copy of the License at -// *

-// * http://www.apache.org/licenses/LICENSE-2.0 -// *

-// * Unless required by applicable law or agreed to in writing, software distributed under the License -// * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express -// * or implied. See the License for the specific language governing permissions and limitations under -// * the License. -// */ -// -//package com.webank.webase.front.tool; -// -//import com.webank.webase.front.base.code.ConstantCode; -//import com.webank.webase.front.base.exception.FrontException; -//import com.webank.webase.front.base.response.BaseResponse; -//import com.webank.webase.front.tool.entity.ReqDecodeParam; -//import com.webank.webase.front.tool.entity.ReqPrivateKey; -//import com.webank.webase.front.tool.entity.ReqSign; -//import com.webank.webase.front.tool.entity.RspHash; -//import com.webank.webase.front.tool.entity.RspKeyPair; -//import com.webank.webase.front.tool.entity.RspSignData; -//import com.webank.webase.front.util.CommonUtils; -//import com.webank.webase.front.util.JsonUtils; -//import com.webank.webase.front.web3api.Web3ApiService; -//import io.swagger.annotations.Api; -//import io.swagger.annotations.ApiImplicitParam; -//import io.swagger.annotations.ApiImplicitParams; -//import io.swagger.annotations.ApiOperation; -//import java.io.ByteArrayInputStream; -//import java.io.IOException; -//import javax.validation.Valid; -//import lombok.extern.slf4j.Slf4j; -//import org.apache.commons.lang3.StringUtils; -//import org.fisco.bcos.sdk.v3.codec.ContractCodec; -//import org.fisco.bcos.sdk.v3.codec.ContractCodecException; -//import org.fisco.bcos.sdk.v3.codec.datatypes.generated.Bytes32; -//import org.fisco.bcos.sdk.v3.crypto.keypair.CryptoKeyPair; -//import org.fisco.bcos.sdk.v3.crypto.keypair.ECDSAKeyPair; -//import org.fisco.bcos.sdk.v3.crypto.keypair.SM2KeyPair; -//import org.fisco.bcos.sdk.v3.crypto.keystore.KeyTool; -//import org.fisco.bcos.sdk.v3.crypto.keystore.P12KeyStore; -//import org.fisco.bcos.sdk.v3.crypto.keystore.PEMKeyStore; -//import org.fisco.bcos.sdk.v3.crypto.signature.SignatureResult; -//import org.fisco.bcos.sdk.v3.model.CryptoType; -//import org.fisco.bcos.sdk.v3.transaction.codec.decode.TransactionDecoderService; -//import org.fisco.bcos.sdk.v3.utils.Numeric; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Qualifier; -//import org.springframework.web.bind.annotation.GetMapping; -//import org.springframework.web.bind.annotation.PostMapping; -//import org.springframework.web.bind.annotation.RequestBody; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.RequestParam; -//import org.springframework.web.bind.annotation.RestController; -//import org.springframework.web.multipart.MultipartFile; -// -// -//@Api(value = "/tool", tags = "tools controller") -//@Slf4j -//@RestController -//@RequestMapping("tool") -//public class ToolController { -// -// @Autowired -// private Web3ApiService web3ApiService; -// -// @ApiOperation(value = "decode input/output", notes = "decode tx receipt's input/output") -// @ApiImplicitParam(name = "param", value = "param to be transfer", required = true, dataType = "ReqDecodeParam") -// @PostMapping("/decode") -// public Object decode(@Valid @RequestBody ReqDecodeParam param) { -// log.info("decode output start. param:{}", JsonUtils.toJSONString(param)); -// // todo 自测返回值 -// TransactionDecoderService txDecoder = new TransactionDecoderService(web3ApiService.getCryptoSuite(groupId), false); -// // decode input -// if (param.getDecodeType() == 1) { -// return txDecoder.decodeReceiptMessage(param.getInput()); -// } else if (param.getDecodeType() == 2) { -// String abi = JsonUtils.objToString(param.getAbiList()); -// ContractCodec abiCodec = new ContractCodec(web3ApiService.getCryptoSuite(groupId), false); -// // decode output -// try { -// return abiCodec.decodeMethodAndGetOutputObject(abi, param.getMethodName(), -// param.getOutput()); -// } catch (ContractCodecException e) { -// log.error("abi decode fail:{}", e.getMessage()); -// throw new FrontException(ConstantCode.CONTRACT_ABI_PARSE_JSON_ERROR); -// } -// } -// return new BaseResponse(ConstantCode.PARAM_ERROR); -// } -// -// @ApiOperation(value = "get key pair", notes = "generate key pair of front's encrypt type") -// @ApiImplicitParam(name = "param", value = "private key(hex string), representation of BigInteger", dataType = "ReqPrivateKey") -// @PostMapping("/keypair") -// public RspKeyPair getKeyPair(@Valid @RequestBody ReqPrivateKey param) { -// String privateKey = param.getPrivateKey(); -// CryptoKeyPair keyPair; -// if (StringUtils.isNotBlank(privateKey)) { -// keyPair = web3ApiService.getCryptoSuite(groupId).getKeyPairFactory().createKeyPair(privateKey); -// } else { -// keyPair = web3ApiService.getCryptoSuite(groupId).getKeyPairFactory().generateKeyPair(); -// } -// return new RspKeyPair(keyPair, web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig); -// } -// -// @ApiOperation(value = "get public key's address", notes = "get address from pub") -// @ApiImplicitParam(name = "publicKey", value = "pub key(hex string format), representation of BigInteger", dataType = "String") -// @GetMapping("/address") -// public RspKeyPair getKey(@RequestParam String publicKey) { -// RspKeyPair response = new RspKeyPair(); -// if (web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig == CryptoType.SM_TYPE) { -// response.setAddress(SM2KeyPair.getAddressByPublicKey(publicKey)); -// } else { -// response.setAddress(ECDSAKeyPair.getAddressByPublicKey(publicKey)); -// } -// response.setEncryptType(web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig); -// response.setPublicKey(publicKey); -// return response; -// } -// -// @ApiOperation(value = "get hash value", notes = "get hash value") -// @ApiImplicitParam(name = "input", value = "input to hash(hexString)", dataType = "String") -// @GetMapping("/hash") -// public RspHash getHashValue(@RequestParam String input) { -// String hashValue = web3ApiService.getCryptoSuite(groupId).hash(input); -// return new RspHash(hashValue, web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig); -// } -// -// -// @ApiOperation(value = "get private key of pem", notes = "get private key of pem") -// @ApiImplicitParam(name = "pemFile", value = ".pem file of private key", dataType = "MultipartFile") -// @PostMapping("/decodePem") -// public RspKeyPair decodePem(@RequestParam MultipartFile pemFile) { -// if (pemFile.getSize() == 0) { -// throw new FrontException(ConstantCode.PEM_FORMAT_ERROR); -// } -// String privateKey; -// try { -// PEMKeyStore pemManager = new PEMKeyStore(new ByteArrayInputStream(pemFile.getBytes())); -// privateKey = KeyTool.getHexedPrivateKey(pemManager.getKeyPair().getPrivate()); -// } catch (IOException e) { -// log.error("decodePem error:[]", e); -// throw new FrontException(ConstantCode.PEM_CONTENT_ERROR); -// } -// -// return getRspKeyPair(privateKey); -// } -// -// @ApiOperation(value = "get PrivateKey of p12", notes = "get PrivateKey by p12") -// @ApiImplicitParams({ -// @ApiImplicitParam(name = "p12File", value = ".p12 file of private key", dataType = "MultipartFile"), -// @ApiImplicitParam(name = "p12Password", value = ".p12 file password", dataType = "String") -// }) -// @PostMapping("/decodeP12") -// public RspKeyPair decodeP12(@RequestParam MultipartFile p12File, -// @RequestParam(required = false, defaultValue = "") String p12Password) { -// if (!CommonUtils.notContainsChinese(p12Password)) { -// throw new FrontException(ConstantCode.P12_PASSWORD_NOT_CHINESE); -// } -// if (p12File.getSize() == 0) { -// throw new FrontException(ConstantCode.P12_FILE_ERROR); -// } -// String privateKey; -// try { -// P12KeyStore p12Manager = new P12KeyStore(new ByteArrayInputStream(p12File.getBytes()), p12Password); -// privateKey = KeyTool.getHexedPrivateKey(p12Manager.getKeyPair().getPrivate()); -// } catch (IOException e) { -// log.error("decodeP12 error:[]", e); -// if (e.getMessage().contains("password")) { -// throw new FrontException(ConstantCode.P12_PASSWORD_ERROR); -// } -// throw new FrontException(ConstantCode.P12_FILE_ERROR); -// } -// return getRspKeyPair(privateKey); -// } -// -// private RspKeyPair getRspKeyPair(String privateKey) { -// CryptoKeyPair keyPair = web3ApiService.getCryptoSuite(groupId).getKeyPairFactory().createKeyPair(privateKey); -// return new RspKeyPair(keyPair, web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig); -// } -// -// @ApiOperation(value = "get hash value", notes = "get hash value") -// @ApiImplicitParams({ -// @ApiImplicitParam(name = "input", value = "input to hash(hexString or utf-8)", dataType = "String"), -// @ApiImplicitParam(name = "type", value = " input type input type 1-hexString,2-utf8(default hex)", dataType = "Integer") -// }) -// @GetMapping("/convert2Bytes32") -// public String getBytes32FromStr(@RequestParam String input, @RequestParam(defaultValue = "1") Integer type) { -// Bytes32 bytes32; -// if (type == 1) { -// // hex input todo use java sdk -// bytes32 = CommonUtils.hexStrToBytes32(input); -// } else if (type == 2) { -// // utf8 input -// bytes32 = CommonUtils.utf8StringToBytes32(input); -// } else { -// throw new FrontException(ConstantCode.PARAM_ERROR); -// } -// return Hex.toHexString(bytes32.getValue()); -// } -// -// @ApiOperation(value = "get utf8's hex string", notes = "get hex string") -// @ApiImplicitParam(name = "input", value = "input to convert(utf8 String)", dataType = "String") -// @GetMapping("/utf8ToHexString") -// public String getHexStringFromUtf8(@RequestParam String input) { -// return CommonUtils.utf8StringToHex(input); -// } -// -// @ApiOperation(value = "sign raw data", notes = "sign raw data by private key") -// @ApiImplicitParam(name = "reqSign", value = "raw data & private key", dataType = "ReqSign") -// @PostMapping("/signMsg") -// public RspSignData getSignedData(@Valid @RequestBody ReqSign reqSign) { -// String privateKey = reqSign.getPrivateKey(); -// String rawData = reqSign.getRawData(); -// CryptoKeyPair cryptoKeyPair = web3ApiService.getCryptoSuite(groupId).getKeyPairFactory().createKeyPair(privateKey); -// SignatureResult signatureData = web3ApiService.getCryptoSuite(groupId).sign(Hex.toHexString(rawData.getBytes()), cryptoKeyPair); -// return new RspSignData(signatureData, web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig); -// } -// -// -//} +/** + * Copyright 2014-2020 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package com.webank.webase.front.tool; + +import com.webank.webase.front.base.code.ConstantCode; +import com.webank.webase.front.base.exception.FrontException; +import com.webank.webase.front.base.response.BaseResponse; +import com.webank.webase.front.tool.entity.ReqDecodeParam; +import com.webank.webase.front.tool.entity.ReqPrivateKey; +import com.webank.webase.front.tool.entity.ReqSign; +import com.webank.webase.front.tool.entity.RspHash; +import com.webank.webase.front.tool.entity.RspKeyPair; +import com.webank.webase.front.tool.entity.RspSignData; +import com.webank.webase.front.transaction.TransService; +import com.webank.webase.front.util.CommonUtils; +import com.webank.webase.front.util.JsonUtils; +import com.webank.webase.front.web3api.Web3ApiService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import javax.validation.Valid; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.fisco.bcos.sdk.v3.codec.ContractCodec; +import org.fisco.bcos.sdk.v3.codec.ContractCodecException; +import org.fisco.bcos.sdk.v3.codec.datatypes.generated.Bytes32; +import org.fisco.bcos.sdk.v3.codec.wrapper.ABIDefinition; +import org.fisco.bcos.sdk.v3.crypto.keypair.CryptoKeyPair; +import org.fisco.bcos.sdk.v3.crypto.keypair.ECDSAKeyPair; +import org.fisco.bcos.sdk.v3.crypto.keypair.SM2KeyPair; +import org.fisco.bcos.sdk.v3.crypto.keystore.KeyTool; +import org.fisco.bcos.sdk.v3.crypto.keystore.P12KeyStore; +import org.fisco.bcos.sdk.v3.crypto.keystore.PEMKeyStore; +import org.fisco.bcos.sdk.v3.crypto.signature.SignatureResult; +import org.fisco.bcos.sdk.v3.model.CryptoType; +import org.fisco.bcos.sdk.v3.transaction.codec.decode.TransactionDecoderService; +import org.fisco.bcos.sdk.v3.utils.Hex; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + + +@Api(value = "/tool", tags = "tools controller") +@Slf4j +@RestController +@RequestMapping("tool") +public class ToolController { + + @Autowired + private Web3ApiService web3ApiService; + + @ApiOperation(value = "decode input/output", notes = "decode tx receipt's input/output") + @ApiImplicitParam(name = "param", value = "param to be transfer", required = true, dataType = "ReqDecodeParam") + @PostMapping("/decode") + public Object decode(@Valid @RequestBody ReqDecodeParam param) { + log.info("decode output start. param:{}", JsonUtils.toJSONString(param)); + // todo 自测返回值 + String groupId = param.getGroupId(); + TransactionDecoderService txDecoder = new TransactionDecoderService(web3ApiService.getCryptoSuite(groupId), false); + ContractCodec abiCodec = new ContractCodec(web3ApiService.getCryptoSuite(groupId), false); + String abi = JsonUtils.objToString(param.getAbiList()); + ABIDefinition abiDefinition = TransService.getFunctionAbiDefinition(param.getMethodName(), abi); + // decode input + if (param.getDecodeType() == 1) { + try { + return abiCodec.decodeMethodInput(abiDefinition, param.getInput()); + } catch (ContractCodecException e) { + log.error("decodeMethodInput ", e); + } + } else if (param.getDecodeType() == 2) { + // decode output + try { + return abiCodec.decodeMethodAndGetOutputObject(abi, param.getMethodName(), + param.getOutput()); + } catch (ContractCodecException e) { + log.error("abi decode fail:{}", e.getMessage()); + throw new FrontException(ConstantCode.PARAM_FAIL_ABI_INVALID); + } + } + return new BaseResponse(ConstantCode.PARAM_ERROR); + } + + @ApiOperation(value = "get key pair", notes = "generate key pair of front's encrypt type") + @ApiImplicitParam(name = "param", value = "private key(hex string), representation of BigInteger", dataType = "ReqPrivateKey") + @PostMapping("/keypair") + public RspKeyPair getKeyPair(@Valid @RequestBody ReqPrivateKey param) { + String groupId = param.getGroupId(); + String privateKey = param.getPrivateKey(); + CryptoKeyPair keyPair; + if (StringUtils.isNotBlank(privateKey)) { + keyPair = web3ApiService.getCryptoSuite(groupId).getKeyPairFactory().createKeyPair(privateKey); + } else { + keyPair = web3ApiService.getCryptoSuite(groupId).getKeyPairFactory().generateKeyPair(); + } + return new RspKeyPair(keyPair, web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig); + } + + @ApiOperation(value = "get public key's address", notes = "get address from pub") + @ApiImplicitParam(name = "publicKey", value = "pub key(hex string format), representation of BigInteger", dataType = "String") + @GetMapping("/address") + public RspKeyPair getKey(@RequestParam String publicKey, + @RequestParam(defaultValue = "group0") String groupId) { + RspKeyPair response = new RspKeyPair(); + if (web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig == CryptoType.SM_TYPE) { + response.setAddress(SM2KeyPair.getAddressByPublicKey(publicKey)); + } else { + response.setAddress(ECDSAKeyPair.getAddressByPublicKey(publicKey)); + } + response.setEncryptType(web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig); + response.setPublicKey(publicKey); + return response; + } + + @ApiOperation(value = "get hash value", notes = "get hash value") + @ApiImplicitParam(name = "input", value = "input to hash(hexString)", dataType = "String") + @GetMapping("/hash") + public RspHash getHashValue(@RequestParam String input, + @RequestParam(defaultValue = "group0") String groupId) { + String hashValue = web3ApiService.getCryptoSuite(groupId).hash(input); + return new RspHash(hashValue, web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig); + } + + + @ApiOperation(value = "get private key of pem", notes = "get private key of pem") + @ApiImplicitParam(name = "pemFile", value = ".pem file of private key", dataType = "MultipartFile") + @PostMapping("/decodePem") + public RspKeyPair decodePem(@RequestParam MultipartFile pemFile, + @RequestParam(defaultValue = "group0") String groupId) { + if (pemFile.getSize() == 0) { + throw new FrontException(ConstantCode.PEM_FORMAT_ERROR); + } + String privateKey; + try { + PEMKeyStore pemManager = new PEMKeyStore(new ByteArrayInputStream(pemFile.getBytes())); + privateKey = KeyTool.getHexedPrivateKey(pemManager.getKeyPair().getPrivate()); + } catch (IOException e) { + log.error("decodePem error:[]", e); + throw new FrontException(ConstantCode.PEM_CONTENT_ERROR); + } + + return getRspKeyPair(groupId, privateKey); + } + + @ApiOperation(value = "get PrivateKey of p12", notes = "get PrivateKey by p12") + @ApiImplicitParams({ + @ApiImplicitParam(name = "p12File", value = ".p12 file of private key", dataType = "MultipartFile"), + @ApiImplicitParam(name = "p12Password", value = ".p12 file password", dataType = "String") + }) + @PostMapping("/decodeP12") + public RspKeyPair decodeP12(@RequestParam MultipartFile p12File, + @RequestParam(required = false, defaultValue = "") String p12Password, + @RequestParam(defaultValue = "group0") String groupId) { + if (!CommonUtils.notContainsChinese(p12Password)) { + throw new FrontException(ConstantCode.P12_PASSWORD_NOT_CHINESE); + } + if (p12File.getSize() == 0) { + throw new FrontException(ConstantCode.P12_FILE_ERROR); + } + String privateKey; + try { + P12KeyStore p12Manager = new P12KeyStore(new ByteArrayInputStream(p12File.getBytes()), p12Password); + privateKey = KeyTool.getHexedPrivateKey(p12Manager.getKeyPair().getPrivate()); + } catch (IOException e) { + log.error("decodeP12 error:[]", e); + if (e.getMessage().contains("password")) { + throw new FrontException(ConstantCode.P12_PASSWORD_ERROR); + } + throw new FrontException(ConstantCode.P12_FILE_ERROR); + } + return getRspKeyPair(groupId, privateKey); + } + + private RspKeyPair getRspKeyPair(String groupId, String privateKey) { + CryptoKeyPair keyPair = web3ApiService.getCryptoSuite(groupId).getKeyPairFactory().createKeyPair(privateKey); + return new RspKeyPair(keyPair, web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig); + } + + @ApiOperation(value = "get hash value", notes = "get hash value") + @ApiImplicitParams({ + @ApiImplicitParam(name = "input", value = "input to hash(hexString or utf-8)", dataType = "String"), + @ApiImplicitParam(name = "type", value = " input type input type 1-hexString,2-utf8(default hex)", dataType = "Integer") + }) + @GetMapping("/convert2Bytes32") + public String getBytes32FromStr(@RequestParam String input, @RequestParam(defaultValue = "1") Integer type, + @RequestParam(defaultValue = "group0") String groupId) { + Bytes32 bytes32; + if (type == 1) { + // hex input todo use java sdk + bytes32 = CommonUtils.hexStrToBytes32(input); + } else if (type == 2) { + // utf8 input + bytes32 = CommonUtils.utf8StringToBytes32(input); + } else { + throw new FrontException(ConstantCode.PARAM_ERROR); + } + return Hex.toHexString(bytes32.getValue()); + } + + @ApiOperation(value = "get utf8's hex string", notes = "get hex string") + @ApiImplicitParam(name = "input", value = "input to convert(utf8 String)", dataType = "String") + @GetMapping("/utf8ToHexString") + public String getHexStringFromUtf8(@RequestParam String input) { + return CommonUtils.utf8StringToHex(input); + } + + @ApiOperation(value = "sign raw data", notes = "sign raw data by private key") + @ApiImplicitParam(name = "reqSign", value = "raw data & private key", dataType = "ReqSign") + @PostMapping("/signMsg") + public RspSignData getSignedData(@Valid @RequestBody ReqSign reqSign) { + String privateKey = reqSign.getPrivateKey(); + String rawData = reqSign.getRawData(); + String groupId = reqSign.getGroupId(); + CryptoKeyPair cryptoKeyPair = web3ApiService.getCryptoSuite(groupId).getKeyPairFactory().createKeyPair(privateKey); + SignatureResult signatureData = web3ApiService.getCryptoSuite(groupId).sign(Hex.toHexString(rawData.getBytes()), cryptoKeyPair); + return new RspSignData(signatureData, web3ApiService.getCryptoSuite(groupId).cryptoTypeConfig); + } + + +} diff --git a/src/main/java/com/webank/webase/front/tool/entity/ReqDecodeParam.java b/src/main/java/com/webank/webase/front/tool/entity/ReqDecodeParam.java index e78c53313..37c096c93 100644 --- a/src/main/java/com/webank/webase/front/tool/entity/ReqDecodeParam.java +++ b/src/main/java/com/webank/webase/front/tool/entity/ReqDecodeParam.java @@ -37,4 +37,6 @@ public class ReqDecodeParam { * add in 1.5.0, not null if decode output */ private String methodName; + @NotNull + private String groupId; } diff --git a/src/main/java/com/webank/webase/front/tool/entity/ReqPrivateKey.java b/src/main/java/com/webank/webase/front/tool/entity/ReqPrivateKey.java index 6437960ff..b39891b0c 100644 --- a/src/main/java/com/webank/webase/front/tool/entity/ReqPrivateKey.java +++ b/src/main/java/com/webank/webase/front/tool/entity/ReqPrivateKey.java @@ -14,6 +14,7 @@ package com.webank.webase.front.tool.entity; +import javax.validation.constraints.NotNull; import lombok.Data; import lombok.NoArgsConstructor; @@ -25,4 +26,6 @@ public class ReqPrivateKey { * string of BigInteger */ private String privateKey; + @NotNull + private String groupId; } diff --git a/src/main/java/com/webank/webase/front/tool/entity/ReqSign.java b/src/main/java/com/webank/webase/front/tool/entity/ReqSign.java index cee666970..2cce6e057 100644 --- a/src/main/java/com/webank/webase/front/tool/entity/ReqSign.java +++ b/src/main/java/com/webank/webase/front/tool/entity/ReqSign.java @@ -14,12 +14,15 @@ package com.webank.webase.front.tool.entity; +import javax.validation.constraints.NotNull; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class ReqSign { + @NotNull + private String groupId; private String rawData; private String privateKey; } From 95d65b1cc2b96b9a41abe3df3faf72f0e6ab840e Mon Sep 17 00:00:00 2001 From: CodingCattwo <847701726@qq.com> Date: Tue, 29 Aug 2023 15:14:34 +0800 Subject: [PATCH 2/6] add wx test api --- .../front/configapi/ConfigController.java | 159 +++++++++++++++++- .../front/configapi/entity/RspAccessWx.java | 34 ++++ .../webank/webase/front/base/ConfigTest.java | 31 ++++ 3 files changed, 223 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/webank/webase/front/configapi/entity/RspAccessWx.java create mode 100644 src/test/java/com/webank/webase/front/base/ConfigTest.java diff --git a/src/main/java/com/webank/webase/front/configapi/ConfigController.java b/src/main/java/com/webank/webase/front/configapi/ConfigController.java index 222bf2311..4dbe48b0b 100644 --- a/src/main/java/com/webank/webase/front/configapi/ConfigController.java +++ b/src/main/java/com/webank/webase/front/configapi/ConfigController.java @@ -16,12 +16,19 @@ package com.webank.webase.front.configapi; +import com.fasterxml.jackson.databind.JsonNode; import com.webank.webase.front.base.code.ConstantCode; import com.webank.webase.front.base.config.Web3Config; +import com.webank.webase.front.base.exception.FrontException; import com.webank.webase.front.base.properties.VersionProperties; import com.webank.webase.front.base.response.BaseResponse; import com.webank.webase.front.configapi.entity.ConfigInfo; import com.webank.webase.front.configapi.entity.ReqSdkConfig; +import com.webank.webase.front.configapi.entity.RspAccessWx; +import com.webank.webase.front.tool.entity.ReqSign; +import com.webank.webase.front.tool.entity.RspSignData; +import com.webank.webase.front.util.CommonUtils; +import com.webank.webase.front.util.JsonUtils; import com.webank.webase.front.version.VersionService; import com.webank.webase.front.web3api.Web3ApiService; import io.swagger.annotations.Api; @@ -31,13 +38,23 @@ import java.util.Map; import javax.validation.Valid; import lombok.extern.slf4j.Slf4j; +import org.fisco.bcos.sdk.v3.crypto.keypair.CryptoKeyPair; +import org.fisco.bcos.sdk.v3.crypto.signature.SignatureResult; +import org.fisco.bcos.sdk.v3.utils.Hex; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; /** * get or update config local @@ -57,7 +74,8 @@ public class ConfigController { private VersionService versionService; @Autowired private ConfigService configService; - + @Autowired + private RestTemplate restTemplate; @GetMapping("encrypt/{groupId}") public Integer getEncryptType(@PathVariable("groupId") String groupId) { @@ -116,4 +134,143 @@ public String getSignVersion() { return versionService.getSignServerVersion(); } + /** + * 校验wx后台 + * @param signature + * @param timestamp + * @param nonce + * @param echostr + * @return + */ + @GetMapping("") + public String checkFromWxServer(@RequestParam(name = "signature") String signature, + @RequestParam(name = "timestamp") String timestamp, + @RequestParam(name = "nonce") String nonce, + @RequestParam(name = "echostr") String echostr) { + log.info("checkFromWxServer {}|{}|{}|{}", signature, timestamp, nonce, echostr); + /* + 1)将token、timestamp、nonce三个参数进行字典序排序 + + 2)将三个参数字符串拼接成一个字符串进行sha1加密 + + 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信 + */ + return echostr; + } + + private static final String appid = "wx8d2d1aa9f12503e5"; + private static final String secret = "bbcfadefc052625fdc17f80e9987bad8"; + + /** + * 此处的token是基础token + * {"access_token":"72_nx2rZymJ-nDBkyE4GQrr8OGfTbfUFb7TvEnbe4uAK-KFw_-DQ6kJeExcBpTwEnUvLSYji8nfmAgZuLKhxiKpDewnIi9fk3ai0VQbZGoauG7hxWc3FhHKi8xKFuUZWZiAGAFCF","expires_in":7200} + * 拿到基础token后,可以获取用户信息 接口为:https://api.weixin.qq.com/cgi-bin/user/info? + * access_token=72_mVN2QSiqNpx31vaJdhaWxp5b7B14_K7n5jsGgbTuGKC8Z6kCRDAR5I_bO1GQ8XiaIeH8b_LbuP1OscUDxxGXhIZ3M_EIqi4AIF7nT-bZPgRhjSlVkseD4LipGzAVRCjAAANJU&openid=oQ3dT6SSdJOIMiIk20JNezcyDYnI + * @return + */ + @GetMapping("/loginwxbase") + public String loginwx() { + log.info("loginwx {}|{}, code:{},access_token:{}", appid, secret); + String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; + log.info("loginwx url: {}", url); + String finalUrl = String.format(url, appid, secret); + log.info("loginwx url: {}", finalUrl); + /* + GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET + {"access_token":"ACCESS_TOKEN","expires_in":7200} + */ + String response = restTemplateExchange(finalUrl, HttpMethod.GET, null, String.class); + log.info("loginwx response: {}", response); + + return response; + } + + /** + * wxOpenId response: + *{"access_token":"72_x3ndcM1sAfaAIVGQPL4RvnVK_p-iCepw9mAQLBkKPTuXTOop2kFEwzTVXkHGOpjKTedp3YmJ2nsjT7B1o4pL2JsHZhDZi9c8-kUFKR-3mcY","expires_in":7200,"refresh_token":"72_K9moQzPW78pFeFiD-5sAao_oZTVRO-hX1ecbY9Zexd4zmghQagF7YFGn68xJHiHJd5Ro0vi3E5tIHBm1zWamSsF_deWkgCgYVAs4PXNITxg", + * "openid":"oQ3dT6SSdJOIMiIk20JNezcyDYnI","scope":"snsapi_base"} + * 根据code获取 授权token + * @param code + * @return + */ + @GetMapping("/wxopenid") + public String wxOpenId( + @RequestParam(name = "code", required = false) String code + ) { + log.info("wxOpenId {}|{}, code:{},access_token:{}", appid, secret, code); + String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"; + log.info("wxOpenId url: {}", url); + String finalUrl = String.format(url, appid, secret, code); + log.info("wxOpenId url: {}", finalUrl); + String response = restTemplateExchange(finalUrl, HttpMethod.GET, null, String.class); + log.info("wxOpenId response: {}", response); + + return response; + } + + + /** + * 拿到授权的token后,传入openid查询基础信息 + * userInfo: { + * "openid":"oQ3dT6SSdJOIMiIk20JNezcyDYnI", + * "nickname":"ç«è´°",// 乱码 + * "sex":0,"language":"","city":"","province":"","country":"", + * "headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/Uy5MVM2s7uKJtciafzaIbag8uUnyw98C1pAEV20ib7qojv14OFEeic8RndypibjFrjVlm2rzAU0wDsGQAZiaIh8DGDg\/132","privilege":[]} + * @param openid + * @param access_token + * @return + */ + @GetMapping("/wxuserInfo") + public String userInfo( + @RequestParam(name = "code", required = false) String code, + @RequestParam(name = "openid", required = false) String openid, + @RequestParam(name = "access_token", required = false) String access_token + ) { + + log.info("wxOpenId {}|{}, code:{},access_token:{}", appid, secret, code); + String urlAuth = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"; + String urlAuthFinal = String.format(urlAuth, appid, secret, code); + log.info("wxOpenId url: {}", urlAuthFinal); + String response = restTemplateExchange(urlAuthFinal, HttpMethod.GET, null, String.class); + RspAccessWx rspAccessWx = JsonUtils.toJavaObject(response, RspAccessWx.class); + log.info("wxOpenId rspAccessWx: {}", rspAccessWx); + openid = rspAccessWx.getOpenid(); + access_token = rspAccessWx.getAccess_token(); + log.info("userInfo {}|{}, openid:{},access_token:{}", appid, secret, + openid, access_token); + String url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"; + log.info("userInfo url: {}", url); + String finalUrl = String.format(url, access_token, openid); + log.info("userInfo url: {}", finalUrl); + String userInfo = restTemplateExchange(finalUrl, HttpMethod.GET, null, String.class); + log.info("userInfo response: {}", userInfo); + + return userInfo; + } + + + private T restTemplateExchange(String url, HttpMethod method, Object param, Class clazz) { + try{ + log.info("restTemplateExchange url:{}, param:{}", url, param); + HttpEntity entity = CommonUtils.buildHttpEntity(param); + ResponseEntity response = restTemplate.exchange(url, method, entity, clazz); + return response.getBody(); + } catch (ResourceAccessException ex) { + log.error("getSignUserEntity fail restTemplateExchange", ex); + throw new FrontException(ConstantCode.DATA_SIGN_NOT_ACCESSIBLE); + } catch (HttpStatusCodeException e) { + JsonNode error = JsonUtils.stringToJsonNode(e.getResponseBodyAsString()); + if (error == null) { + throw e; + } + log.error("getSignUserEntity http request fail. error:{}", JsonUtils.toJSONString(error)); + // if return 404, no code or errorMessage + int code = error.get("code").intValue(); + String errorMessage = error.get("errorMessage").asText(); + throw new FrontException(code, errorMessage); + } + } + + + } diff --git a/src/main/java/com/webank/webase/front/configapi/entity/RspAccessWx.java b/src/main/java/com/webank/webase/front/configapi/entity/RspAccessWx.java new file mode 100644 index 000000000..e970dbbdf --- /dev/null +++ b/src/main/java/com/webank/webase/front/configapi/entity/RspAccessWx.java @@ -0,0 +1,34 @@ +/** + * Copyright 2014-2021 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package com.webank.webase.front.configapi.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * {"access_token":"72_x3ndcM1sAfaAIVGQPL4RvnVK_p-iCepw9mAQLBkKPTuXTOop2kFEwzTVXkHGOpjKTedp3YmJ2nsjT7B1o4pL2JsHZhDZi9c8-kUFKR-3mcY", + * "expires_in":7200, + * "refresh_token":"72_K9moQzPW78pFeFiD-5sAao_oZTVRO-hX1ecbY9Zexd4zmghQagF7YFGn68xJHiHJd5Ro0vi3E5tIHBm1zWamSsF_deWkgCgYVAs4PXNITxg", + * "openid":"oQ3dT6SSdJOIMiIk20JNezcyDYnI", + * "scope":"snsapi_base"} + */ +@Data +public class RspAccessWx { + private String access_token; + private String refresh_token; + private String openid; + private String scope; + private Long expires_in; +} diff --git a/src/test/java/com/webank/webase/front/base/ConfigTest.java b/src/test/java/com/webank/webase/front/base/ConfigTest.java new file mode 100644 index 000000000..e30f2b403 --- /dev/null +++ b/src/test/java/com/webank/webase/front/base/ConfigTest.java @@ -0,0 +1,31 @@ +/** + * Copyright 2014-2021 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package com.webank.webase.front.base; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import org.junit.Test; + +public class ConfigTest { + + @Test + public void test() throws UnsupportedEncodingException { + String url = "http://139.159.152.228:5002/WeBASE-Front/config/wxopenid"; + String output = URLEncoder.encode(url, "GBK"); + System.out.println(output); + + } + +} From 00805c12dcfb202e90593791dfeaba442a202d5d Mon Sep 17 00:00:00 2001 From: CodingCattwo <847701726@qq.com> Date: Fri, 19 Jan 2024 14:45:36 +0800 Subject: [PATCH 3/6] update version 3.1.1 --- release_note.txt | 2 +- src/main/resources/application-docker.yml | 2 +- src/main/resources/application.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/release_note.txt b/release_note.txt index 2c854bcac..70cdc0898 100644 --- a/release_note.txt +++ b/release_note.txt @@ -1 +1 @@ -v3.0.2 \ No newline at end of file +v3.1.1 \ No newline at end of file diff --git a/src/main/resources/application-docker.yml b/src/main/resources/application-docker.yml index a9d59f6b9..3d4405f90 100644 --- a/src/main/resources/application-docker.yml +++ b/src/main/resources/application-docker.yml @@ -1,5 +1,5 @@ # server version -version: v3.0.2 +version: v3.1.1 server: port: ${SERVER_PORT:5002} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 2ddfbdfe6..f87bfc3d9 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,5 +1,5 @@ # server version -version: v3.0.2 +version: v3.1.1 server: port: 5002 From c5c60abe95edcfae28d2bc565808a18b62cb1235 Mon Sep 17 00:00:00 2001 From: CodingCattwo <847701726@qq.com> Date: Fri, 19 Jan 2024 14:54:03 +0800 Subject: [PATCH 4/6] update changelog --- Changelog.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Changelog.md b/Changelog.md index ae02e0557..f75343dca 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,19 @@ +### v3.1.1(2024-01-19) + +**Add** +- 系统配置中增加`auth_check_status`配置,用于启用权限控制功能 + +**Fix** +- 修复预编译合约中报错权限不足的bug,如修改共识类型 + +**兼容性** +- 支持FISCO-BCOS v3.0.0 及以上版本 +- WeBASE-Web v3.1.1及以上版本 +- WeBASE-Node-Manager v3.1.0 + +详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/lab/)。 + + ### v3.1.0(2023-07-20) **Add** @@ -10,7 +26,7 @@ **兼容性** - 支持FISCO-BCOS v3.0.0 及以上版本 -- WeBASE-Node-Manager v3.0.2及以上版本 +- WeBASE-Node-Manager v3.1.0及以上版本 - WeBASE-Sign v3.0.2 详细了解,请阅读[**技术文档**](https://webasedoc.readthedocs.io/zh_CN/lab/)。 From 4f15d9f61b029d967b688b78e9f26d16793fea56 Mon Sep 17 00:00:00 2001 From: CodingCattwo <847701726@qq.com> Date: Fri, 19 Jan 2024 15:26:50 +0800 Subject: [PATCH 5/6] rm wx login & add cryptoMaterial.put(disableSsl, disableSsl); --- .../webase/front/base/config/Web3Config.java | 2 + .../front/configapi/ConfigController.java | 164 ------------------ src/main/resources/application-docker.yml | 1 + src/main/resources/application.yml | 1 + 4 files changed, 4 insertions(+), 164 deletions(-) diff --git a/src/main/java/com/webank/webase/front/base/config/Web3Config.java b/src/main/java/com/webank/webase/front/base/config/Web3Config.java index 651a98124..001f0f28e 100644 --- a/src/main/java/com/webank/webase/front/base/config/Web3Config.java +++ b/src/main/java/com/webank/webase/front/base/config/Web3Config.java @@ -42,6 +42,7 @@ public class Web3Config { private String threadPoolSize; private String certPath; private String useSmSsl; + private String disableSsl; private List peers; @@ -50,6 +51,7 @@ public ConfigOption getConfigOptionFromFile() throws ConfigException { log.info("start init ConfigProperty"); // cert config, encrypt type Map cryptoMaterial = new HashMap<>(); + cryptoMaterial.put("disableSsl", disableSsl); cryptoMaterial.put("certPath", certPath); cryptoMaterial.put("useSMCrypto", useSmSsl); log.info("init cert cryptoMaterial:{}, (using conf as cert path)", JsonUtils.objToString(cryptoMaterial)); diff --git a/src/main/java/com/webank/webase/front/configapi/ConfigController.java b/src/main/java/com/webank/webase/front/configapi/ConfigController.java index 4dbe48b0b..97c4e7c86 100644 --- a/src/main/java/com/webank/webase/front/configapi/ConfigController.java +++ b/src/main/java/com/webank/webase/front/configapi/ConfigController.java @@ -16,44 +16,17 @@ package com.webank.webase.front.configapi; -import com.fasterxml.jackson.databind.JsonNode; -import com.webank.webase.front.base.code.ConstantCode; import com.webank.webase.front.base.config.Web3Config; -import com.webank.webase.front.base.exception.FrontException; import com.webank.webase.front.base.properties.VersionProperties; -import com.webank.webase.front.base.response.BaseResponse; -import com.webank.webase.front.configapi.entity.ConfigInfo; -import com.webank.webase.front.configapi.entity.ReqSdkConfig; -import com.webank.webase.front.configapi.entity.RspAccessWx; -import com.webank.webase.front.tool.entity.ReqSign; -import com.webank.webase.front.tool.entity.RspSignData; -import com.webank.webase.front.util.CommonUtils; -import com.webank.webase.front.util.JsonUtils; import com.webank.webase.front.version.VersionService; import com.webank.webase.front.web3api.Web3ApiService; import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import java.time.Duration; -import java.time.Instant; -import java.util.Map; -import javax.validation.Valid; import lombok.extern.slf4j.Slf4j; -import org.fisco.bcos.sdk.v3.crypto.keypair.CryptoKeyPair; -import org.fisco.bcos.sdk.v3.crypto.signature.SignatureResult; -import org.fisco.bcos.sdk.v3.utils.Hex; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.HttpStatusCodeException; -import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; /** @@ -134,143 +107,6 @@ public String getSignVersion() { return versionService.getSignServerVersion(); } - /** - * 校验wx后台 - * @param signature - * @param timestamp - * @param nonce - * @param echostr - * @return - */ - @GetMapping("") - public String checkFromWxServer(@RequestParam(name = "signature") String signature, - @RequestParam(name = "timestamp") String timestamp, - @RequestParam(name = "nonce") String nonce, - @RequestParam(name = "echostr") String echostr) { - log.info("checkFromWxServer {}|{}|{}|{}", signature, timestamp, nonce, echostr); - /* - 1)将token、timestamp、nonce三个参数进行字典序排序 - - 2)将三个参数字符串拼接成一个字符串进行sha1加密 - - 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信 - */ - return echostr; - } - - private static final String appid = "wx8d2d1aa9f12503e5"; - private static final String secret = "bbcfadefc052625fdc17f80e9987bad8"; - - /** - * 此处的token是基础token - * {"access_token":"72_nx2rZymJ-nDBkyE4GQrr8OGfTbfUFb7TvEnbe4uAK-KFw_-DQ6kJeExcBpTwEnUvLSYji8nfmAgZuLKhxiKpDewnIi9fk3ai0VQbZGoauG7hxWc3FhHKi8xKFuUZWZiAGAFCF","expires_in":7200} - * 拿到基础token后,可以获取用户信息 接口为:https://api.weixin.qq.com/cgi-bin/user/info? - * access_token=72_mVN2QSiqNpx31vaJdhaWxp5b7B14_K7n5jsGgbTuGKC8Z6kCRDAR5I_bO1GQ8XiaIeH8b_LbuP1OscUDxxGXhIZ3M_EIqi4AIF7nT-bZPgRhjSlVkseD4LipGzAVRCjAAANJU&openid=oQ3dT6SSdJOIMiIk20JNezcyDYnI - * @return - */ - @GetMapping("/loginwxbase") - public String loginwx() { - log.info("loginwx {}|{}, code:{},access_token:{}", appid, secret); - String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; - log.info("loginwx url: {}", url); - String finalUrl = String.format(url, appid, secret); - log.info("loginwx url: {}", finalUrl); - /* - GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET - {"access_token":"ACCESS_TOKEN","expires_in":7200} - */ - String response = restTemplateExchange(finalUrl, HttpMethod.GET, null, String.class); - log.info("loginwx response: {}", response); - - return response; - } - - /** - * wxOpenId response: - *{"access_token":"72_x3ndcM1sAfaAIVGQPL4RvnVK_p-iCepw9mAQLBkKPTuXTOop2kFEwzTVXkHGOpjKTedp3YmJ2nsjT7B1o4pL2JsHZhDZi9c8-kUFKR-3mcY","expires_in":7200,"refresh_token":"72_K9moQzPW78pFeFiD-5sAao_oZTVRO-hX1ecbY9Zexd4zmghQagF7YFGn68xJHiHJd5Ro0vi3E5tIHBm1zWamSsF_deWkgCgYVAs4PXNITxg", - * "openid":"oQ3dT6SSdJOIMiIk20JNezcyDYnI","scope":"snsapi_base"} - * 根据code获取 授权token - * @param code - * @return - */ - @GetMapping("/wxopenid") - public String wxOpenId( - @RequestParam(name = "code", required = false) String code - ) { - log.info("wxOpenId {}|{}, code:{},access_token:{}", appid, secret, code); - String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"; - log.info("wxOpenId url: {}", url); - String finalUrl = String.format(url, appid, secret, code); - log.info("wxOpenId url: {}", finalUrl); - String response = restTemplateExchange(finalUrl, HttpMethod.GET, null, String.class); - log.info("wxOpenId response: {}", response); - - return response; - } - - - /** - * 拿到授权的token后,传入openid查询基础信息 - * userInfo: { - * "openid":"oQ3dT6SSdJOIMiIk20JNezcyDYnI", - * "nickname":"ç«è´°",// 乱码 - * "sex":0,"language":"","city":"","province":"","country":"", - * "headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/Uy5MVM2s7uKJtciafzaIbag8uUnyw98C1pAEV20ib7qojv14OFEeic8RndypibjFrjVlm2rzAU0wDsGQAZiaIh8DGDg\/132","privilege":[]} - * @param openid - * @param access_token - * @return - */ - @GetMapping("/wxuserInfo") - public String userInfo( - @RequestParam(name = "code", required = false) String code, - @RequestParam(name = "openid", required = false) String openid, - @RequestParam(name = "access_token", required = false) String access_token - ) { - - log.info("wxOpenId {}|{}, code:{},access_token:{}", appid, secret, code); - String urlAuth = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"; - String urlAuthFinal = String.format(urlAuth, appid, secret, code); - log.info("wxOpenId url: {}", urlAuthFinal); - String response = restTemplateExchange(urlAuthFinal, HttpMethod.GET, null, String.class); - RspAccessWx rspAccessWx = JsonUtils.toJavaObject(response, RspAccessWx.class); - log.info("wxOpenId rspAccessWx: {}", rspAccessWx); - openid = rspAccessWx.getOpenid(); - access_token = rspAccessWx.getAccess_token(); - log.info("userInfo {}|{}, openid:{},access_token:{}", appid, secret, - openid, access_token); - String url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"; - log.info("userInfo url: {}", url); - String finalUrl = String.format(url, access_token, openid); - log.info("userInfo url: {}", finalUrl); - String userInfo = restTemplateExchange(finalUrl, HttpMethod.GET, null, String.class); - log.info("userInfo response: {}", userInfo); - - return userInfo; - } - - - private T restTemplateExchange(String url, HttpMethod method, Object param, Class clazz) { - try{ - log.info("restTemplateExchange url:{}, param:{}", url, param); - HttpEntity entity = CommonUtils.buildHttpEntity(param); - ResponseEntity response = restTemplate.exchange(url, method, entity, clazz); - return response.getBody(); - } catch (ResourceAccessException ex) { - log.error("getSignUserEntity fail restTemplateExchange", ex); - throw new FrontException(ConstantCode.DATA_SIGN_NOT_ACCESSIBLE); - } catch (HttpStatusCodeException e) { - JsonNode error = JsonUtils.stringToJsonNode(e.getResponseBodyAsString()); - if (error == null) { - throw e; - } - log.error("getSignUserEntity http request fail. error:{}", JsonUtils.toJSONString(error)); - // if return 404, no code or errorMessage - int code = error.get("code").intValue(); - String errorMessage = error.get("errorMessage").asText(); - throw new FrontException(code, errorMessage); - } - } - } diff --git a/src/main/resources/application-docker.yml b/src/main/resources/application-docker.yml index 3d4405f90..b61b36080 100644 --- a/src/main/resources/application-docker.yml +++ b/src/main/resources/application-docker.yml @@ -15,6 +15,7 @@ sdk: certPath: conf # sdk cert path of relative or absolute peers: ${PEERS:"['127.0.0.1:20200','127.0.0.1:20201']"} threadPoolSize: 50 # thread pool of sdk + disableSsl: false # disable node ssl or not spring: datasource: diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index f87bfc3d9..a8704cc3a 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -15,6 +15,7 @@ sdk: peers: ['127.0.0.1:20200'] certPath: conf # sdk cert path of relative or absolute, default 'conf' threadPoolSize: 50 # thread pool of sdk + disableSsl: false # disable node ssl or not spring: datasource: From f0807793ce44c75ba1ffcfa4a7ac6400891fe085 Mon Sep 17 00:00:00 2001 From: CodingCattwo <847701726@qq.com> Date: Fri, 19 Jan 2024 15:28:36 +0800 Subject: [PATCH 6/6] delete wx test --- .../front/configapi/entity/RspAccessWx.java | 34 ------------------- .../webank/webase/front/base/ConfigTest.java | 31 ----------------- 2 files changed, 65 deletions(-) delete mode 100644 src/main/java/com/webank/webase/front/configapi/entity/RspAccessWx.java delete mode 100644 src/test/java/com/webank/webase/front/base/ConfigTest.java diff --git a/src/main/java/com/webank/webase/front/configapi/entity/RspAccessWx.java b/src/main/java/com/webank/webase/front/configapi/entity/RspAccessWx.java deleted file mode 100644 index e970dbbdf..000000000 --- a/src/main/java/com/webank/webase/front/configapi/entity/RspAccessWx.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2014-2021 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.webank.webase.front.configapi.entity; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -/** - * {"access_token":"72_x3ndcM1sAfaAIVGQPL4RvnVK_p-iCepw9mAQLBkKPTuXTOop2kFEwzTVXkHGOpjKTedp3YmJ2nsjT7B1o4pL2JsHZhDZi9c8-kUFKR-3mcY", - * "expires_in":7200, - * "refresh_token":"72_K9moQzPW78pFeFiD-5sAao_oZTVRO-hX1ecbY9Zexd4zmghQagF7YFGn68xJHiHJd5Ro0vi3E5tIHBm1zWamSsF_deWkgCgYVAs4PXNITxg", - * "openid":"oQ3dT6SSdJOIMiIk20JNezcyDYnI", - * "scope":"snsapi_base"} - */ -@Data -public class RspAccessWx { - private String access_token; - private String refresh_token; - private String openid; - private String scope; - private Long expires_in; -} diff --git a/src/test/java/com/webank/webase/front/base/ConfigTest.java b/src/test/java/com/webank/webase/front/base/ConfigTest.java deleted file mode 100644 index e30f2b403..000000000 --- a/src/test/java/com/webank/webase/front/base/ConfigTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright 2014-2021 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package com.webank.webase.front.base; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import org.junit.Test; - -public class ConfigTest { - - @Test - public void test() throws UnsupportedEncodingException { - String url = "http://139.159.152.228:5002/WeBASE-Front/config/wxopenid"; - String output = URLEncoder.encode(url, "GBK"); - System.out.println(output); - - } - -}