Commit 1ffe041a authored by muhong's avatar muhong

修改 小程序接口

parent b27f5e7c
......@@ -9,8 +9,7 @@ import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
......@@ -232,6 +231,18 @@ public class OkHttpUtil {
}
}
public InputStream getInputStream() {
setHeader(request);
try {
Response response = okHttpClient.newCall(request.build()).execute();
assert response.body() != null;
return response.body().byteStream();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 异步请求,有返回值
*/
......
package com.wwdz.ch.db.dao;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wwdz.ch.db.domain.Item;
import com.wwdz.ch.db.domain.ItemExample;
import com.wwdz.ch.db.dto.request.CoinRequestDto;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;
public interface ItemDao {
......@@ -92,4 +88,20 @@ public interface ItemDao {
* @return
*/
int count();
/**
* 获取包含images字段的商品列表
*
* @param coinRequestDto
* @return
*/
List<Item> findListWithImages(CoinRequestDto coinRequestDto);
/**
* 商品名称联想,返回16条
*
* @param coinRequestDto
* @return
*/
List<String> findNames(CoinRequestDto coinRequestDto);
}
......@@ -297,4 +297,30 @@ public class ItemDaoImpl implements ItemDao {
return (int) itemMapper.countByExample(example);
}
@Override
public List<Item> findListWithImages(CoinRequestDto coinRequestDto) {
ItemExample example = new ItemExample();
ItemExample.Criteria criteria = example.createCriteria();
JdbcHelper.ifPresent(coinRequestDto.getId(), criteria :: andIdEqualTo);
JdbcHelper.ifPresent(coinRequestDto.getName(), criteria :: andNameLike);
JdbcHelper.ifPresent(coinRequestDto.getCid(), criteria :: andCidEqualTo);
JdbcHelper.ifPresent(coinRequestDto.getIds(), criteria::andIdIn);
return itemMapper.selectByExampleWithBLOBs(example);
}
@Override
public List<String> findNames(CoinRequestDto coinRequestDto) {
ItemExample example = new ItemExample();
ItemExample.Criteria criteria = example.createCriteria();
criteria.andIsDeletedEqualTo(false);
// 暂时去除华夏古泉和天眷堂的钱币, 对应编码1和7
if (!ObjectUtils.isEmpty(coinRequestDto.getIsExcluded()) && coinRequestDto.getIsExcluded() == 1) {
criteria.andSourceNotEqualTo(1);
criteria.andSourceNotEqualTo(7);
}
if (StringUtils.hasLength(coinRequestDto.getName())) {
criteria.andNameLike("%" + coinRequestDto.getName() + "%");
}
return itemMapper.selectNameByExample(example);
}
}
......@@ -2,11 +2,11 @@ package com.wwdz.ch.db.mapper;
import com.wwdz.ch.db.domain.Item;
import com.wwdz.ch.db.domain.ItemExample;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface ItemMapper {
long countByExample(ItemExample example);
......@@ -81,4 +81,6 @@ public interface ItemMapper {
int updateByPrimaryKeyWithBLOBs(Item record);
int updateByPrimaryKey(Item record);
List<String> selectNameByExample(ItemExample example);
}
\ No newline at end of file
......@@ -127,6 +127,7 @@
<insert id="batchInsert" parameterType="com.wwdz.ch.db.domain.FavoritesItemsRelation">
insert into favorites_items_relation (favorites_id, user_id, item_id,
add_time)
values
<foreach collection="list" item="item" separator=",">
(#{item.favoritesId,jdbcType=BIGINT}, #{item.userId,jdbcType=BIGINT}, #{item.itemId,jdbcType=BIGINT}, #{item.addTime,jdbcType=TIMESTAMP})
</foreach>
......
......@@ -29,6 +29,8 @@
<result column="detail" jdbcType="LONGVARCHAR" property="detail" />
<result column="original_extra" jdbcType="LONGVARCHAR" property="originalExtra" />
</resultMap>
<resultMap id="StringResultMap" type="java.lang.String">
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
......@@ -699,4 +701,19 @@
</if>
limit 1
</select>
<select id="selectNameByExample" parameterType="com.wwdz.ch.db.domain.ItemExample" resultMap="StringResultMap">
select
<if test="distinct">
distinct
</if>
name
from item
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
limit 16
</select>
</mapper>
\ No newline at end of file
......@@ -23,8 +23,10 @@ public class ItemRequestDto implements Entity {
private Integer cid;
// 藏品标题
private String name;
// 藏品图片或视频地址,用;分隔
// 藏品图片地址,用;分隔
private String images;
// 藏品视频地址,用;分隔
private String videos;
// 藏品详细信息
private String detail;
// 藏品价格
......
......@@ -3,6 +3,8 @@ package com.wwdz.ch.wx.entity.vo;
import com.xxdxxs.entity.Entity;
import lombok.Data;
import java.util.Map;
@Data
public class ItemResponseVo implements Entity {
private Long id;
......@@ -18,4 +20,7 @@ public class ItemResponseVo implements Entity {
private Long favoritesId;
private long collectCount;
private Integer isMine;
private String createTime;
private String videos;
private Map<String, Object> homePageImage;
}
......@@ -101,7 +101,7 @@ public class FavoritesServiceImpl implements FavoritesService {
CoinRequestDto coinRequestDto = new CoinRequestDto();
coinRequestDto.setIds(favoritesItemsRelations.stream()
.map(FavoritesItemsRelation::getItemId).collect(Collectors.toList()));
List<Item> items = itemDao.findList(coinRequestDto);
List<Item> items = itemDao.findListWithImages(coinRequestDto);
items = items.stream().filter(s -> StringUtils.isNotBlank(s.getImages())).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(items)) {
List<String> images = new ArrayList<>();
......
......@@ -10,13 +10,10 @@ import com.wwdz.ch.wx.entity.request.ItemRequestDto;
import com.wwdz.ch.wx.entity.vo.AgentTranceResponseVo;
import com.wwdz.ch.wx.entity.vo.ItemResponseVo;
import com.wwdz.ch.wx.service.ItemService;
import com.wwdz.ch.wx.service.WxLoginService;
import com.xxdxxs.utils.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -24,8 +21,10 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
@Service
......@@ -43,6 +42,21 @@ public class ItemServiceImpl implements ItemService {
private FootPrintDao footPrintDao;
@Autowired
private FavoritesDao favoritesDao;
@Autowired
private WxLoginService wxLoginService;
@Override
public Result nameList(ItemRequestDto dto) {
try {
CoinRequestDto coinRequestDto = new CoinRequestDto();
coinRequestDto.setName(dto.getName());
List<String> names = itemDao.findNames(coinRequestDto);
return Result.success(names);
} catch (Exception e) {
logger.error("查询藏品名称联想失败", e);
return Result.failed("查询藏品名称联想失败");
}
}
@Override
......@@ -70,7 +84,6 @@ public class ItemServiceImpl implements ItemService {
ItemResponseVo vo = new ItemResponseVo();
vo.setId(item.getId());
vo.setName(item.getName());
vo.setImages(item.getImages());
vo.setPrice(String.valueOf(item.getPrice() * 100));
vo.setDetail(item.getDetail());
vo.setIsCollected(0);
......@@ -117,6 +130,7 @@ public class ItemServiceImpl implements ItemService {
item.setIsStd(false);
item.setSort(100);
item.setImages(dto.getImages());
item.setVedios(dto.getVideos());
item.setPrice(Long.parseLong(dto.getPrice()) / 100);
item.setDetail(dto.getDetail());
Date now = new Date();
......@@ -161,6 +175,7 @@ public class ItemServiceImpl implements ItemService {
itemResponseVo.setId(item.getId());
itemResponseVo.setName(item.getName());
itemResponseVo.setImages(item.getImages());
itemResponseVo.setVideos(item.getVedios());
itemResponseVo.setDetail(item.getDetail());
itemResponseVo.setCid(item.getCid());
Category category = categoryDao.findById(item.getCid());
......@@ -169,6 +184,7 @@ public class ItemServiceImpl implements ItemService {
}
itemResponseVo.setPrice(String.valueOf(item.getPrice() * 100));
itemResponseVo.setSourceType(item.getSourceType());
itemResponseVo.setCreateTime(DateUtils.toString(item.getCreateTime()));
itemResponseVo.setIsCollected(0);
itemResponseVo.setIsMine(0);
if (!dto.getUserId().equals(0L)) {
......@@ -208,7 +224,7 @@ public class ItemServiceImpl implements ItemService {
}
// 判断是否收藏过
if (favoritesItemsRelationDao.isCollected(dto.getUserId(), dto.getId())) {
Result.failed("您已经收藏过该藏品");
return Result.failed("您已经收藏过该藏品");
}
// 查找默认收藏册
Favorites favorites = favoritesDao.defaultFavorites(dto.getUserId());
......@@ -221,6 +237,7 @@ public class ItemServiceImpl implements ItemService {
favoritesItemsRelation.setUserId(dto.getUserId());
favoritesItemsRelation.setFavoritesId(favorites.getId());
favoritesItemsRelation.setItemId(dto.getId());
favoritesItemsRelation.setAddTime(new Date());
favoritesItemsRelationDao.insert(favoritesItemsRelation);
Map<String, Object> map = new HashMap<>();
......@@ -263,6 +280,7 @@ public class ItemServiceImpl implements ItemService {
item.setName(dto.getName());
item.setCid(dto.getCid());
item.setImages(dto.getImages());
item.setVedios(dto.getVideos());
item.setPrice(Long.parseLong(dto.getPrice()) / 100);
item.setDetail(dto.getDetail());
Date now = new Date();
......@@ -278,7 +296,10 @@ public class ItemServiceImpl implements ItemService {
favoritesItemsRelation.setFavoritesId(dto.getFavoritesId());
favoritesItemsRelation.setItemId(item.getId());
favoritesItemsRelationDao.insert(favoritesItemsRelation);
return Result.success();
Map<String, Object> map = new HashMap<>();
map.put("id", dto.getId());
return Result.success(map);
} catch (Exception e) {
logger.error("修改藏品失败,原因:" + e.getMessage(), e);
return Result.failed("修改藏品失败");
......@@ -286,25 +307,52 @@ public class ItemServiceImpl implements ItemService {
}
@Override
public Result test() {
public void getWxacode(String page, String scene, HttpServletResponse response) {
try {
String url = "https://cdn.wanwudezhi.com/static/web-static/video/53596700878a572ca4fae35243aaa819.mp4?vframe/jpg/offset/0";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
HttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
InputStream inputStream = wxLoginService.getWxacodeStream(page, scene);
if (Objects.isNull(inputStream)) {
response.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
return;
}
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while ((len = inputStream.read(buffer)) != -1) {
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
byte[] bytes = outputStream.toByteArray();
return Result.success(Base64.getEncoder().encodeToString(bytes));
//关闭输入流
inputStream.close();
//把outStream里的数据写入内存
byte[] data = outStream.toByteArray();
OutputStream outputStream = response.getOutputStream();//输出数据
//写入数据
outputStream.write(data);
outputStream.flush();
//关闭输出流
outStream.close();
} catch (Exception e) {
logger.error("获取小程序码失败", e);
response.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
}
}
@Override
public Result getWxLink(String pageUrl) {
try {
String link = wxLoginService.getLink(pageUrl);
if (StringUtils.isBlank(link)) {
return Result.failed("获取小程序链接失败");
}
Map<String, Object> map = new HashMap<>();
map.put("link", link);
return Result.success(map);
} catch (Exception e) {
logger.error("error", e);
return Result.failed(e.getMessage());
logger.error("获取小程序链接失败", e);
return Result.failed("获取小程序链接失败");
}
}
}
......@@ -17,6 +17,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
......@@ -26,13 +27,10 @@ public class WxLoginServiceImpl implements WxLoginService {
private static final String appid = "wx5b4409448bf2c72b";
private static final String secret = "6fee0d7b2197845fed0a3fe8f5a9bd66";
// private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/stable_token";
private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";
private static final String GET_WXACODE_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%s";
private static final String GET_WXACODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";
private static final String GET_LINK_URL = "https://api.weixin.qq.com/wxa/genwxashortlink?access_token=%s";
@Autowired
private WxMaService wxMaService;
......@@ -96,6 +94,7 @@ public class WxLoginServiceImpl implements WxLoginService {
logger.info("开始获取access_token----------------");
try {
if (redisUtil.hasKey(CacheCodeConstants.WX_ACCESS_TOKEN)) {
logger.info("从redis获取access_token成功");
return redisUtil.get(CacheCodeConstants.WX_ACCESS_TOKEN).toString();
} else {
String accessTokenUrl = String.format(GET_ACCESS_TOKEN_URL, appid, secret);
......@@ -116,4 +115,44 @@ public class WxLoginServiceImpl implements WxLoginService {
return null;
}
}
@Override
public InputStream getWxacodeStream(String page, String scene) {
try {
String accessToken = getAccessToken();
String url = String.format(GET_WXACODE_URL, accessToken);
Map<String, Object> param = new HashMap<>();
param.put("page", page);
param.put("scene", scene);
param.put("check_path", false);
InputStream inputStream = OkHttpUtil.builder().url(url).addParams(param).post(true).getInputStream();
return inputStream;
} catch (Exception e) {
logger.error("从微信获取小程序码流失败", e);
return null;
}
}
@Override
public String getLink (String pageUrl) {
try {
String accessToken = getAccessToken();
String url = String.format(GET_LINK_URL, accessToken);
Map<String, Object> param = new HashMap<>();
param.put("page_url", pageUrl);
String result = OkHttpUtil.builder().url(url).addParams(param).post(true).sync();
logger.info("获取小程序链接结果:" + result);
System.out.println(result);
if (!result.contains("link")) {
return null;
}
if (!StringUtils.equals("0", JsonUtils.getValueByPath(result, "errcode"))) {
return null;
}
return JsonUtils.getValueByPath(result, "link");
} catch (Exception e) {
logger.error("从微信获取小程序短链接失败", e);
return null;
}
}
}
......@@ -3,7 +3,10 @@ package com.wwdz.ch.wx.service;
import com.wwdz.ch.core.type.Result;
import com.wwdz.ch.wx.entity.request.ItemRequestDto;
import javax.servlet.http.HttpServletResponse;
public interface ItemService {
Result nameList(ItemRequestDto dto);
Result page(ItemRequestDto dto);
Result list(ItemRequestDto dto);
......@@ -18,5 +21,6 @@ public interface ItemService {
Result update(ItemRequestDto dto);
Result test();
void getWxacode(String page, String scene, HttpServletResponse response);
Result getWxLink(String pageUrl);
}
......@@ -2,8 +2,11 @@ package com.wwdz.ch.wx.service;
import com.wwdz.ch.wx.entity.request.UserRequestDto;
import java.io.InputStream;
public interface WxLoginService {
String getPhone(UserRequestDto dto);
String getAccessToken();
InputStream getWxacodeStream(String path, String scene);
String getLink (String pageUrl);
}
......@@ -11,11 +11,10 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
......@@ -29,6 +28,21 @@ public class WxItemController {
@Autowired
private WxLoginService wxLoginService;
@ApiOperation(value = "藏品名称联想")
@PostMapping("/findNames")
public Result findNames(@RequestBody KlDataRequestDto klDataRequestDto) {
String json = klDataRequestDto.getKl_data();
logger.info("【请求开始】藏品名称联想,请求参数,kl_data:{}", json);
String name = JsonUtils.getValueByPath(json, "name");
if (StringUtils.isBlank(name)) {
return Result.success(new ArrayList<>());
}
ItemRequestDto dto = new ItemRequestDto();
dto.setName(name);
return itemService.nameList(dto);
}
@ApiOperation(value = "分页查询")
@PostMapping("/page")
public Result page(@RequestBody KlDataRequestDto klDataRequestDto) {
......@@ -72,6 +86,7 @@ public class WxItemController {
String name = JsonUtils.getValueByPath(json, "name");
String detail = JsonUtils.getValueByPath(json, "detail");
String images = JsonUtils.getValueByPath(json, "images");
String videos = JsonUtils.getValueByPath(json, "videos");
String favoritesId = JsonUtils.getValueByPath(json, "favoritesId");
String price = JsonUtils.getValueByPath(json, "price");
if (StringUtils.isBlank(userId)) {
......@@ -87,7 +102,7 @@ public class WxItemController {
return Result.failed("价格不能为空");
}
if (StringUtils.isBlank(images)) {
return Result.failed("图片或视频不能为空");
return Result.failed("图片不能为空");
}
if (StringUtils.isBlank(favoritesId)) {
return Result.failed("收藏册id不能为空");
......@@ -100,6 +115,7 @@ public class WxItemController {
dto.setDetail(detail);
dto.setFavoritesId(Long.parseLong(favoritesId));
dto.setImages(images);
dto.setVideos(videos);
dto.setPrice(price);
return itemService.add(dto);
}
......@@ -115,6 +131,7 @@ public class WxItemController {
String name = JsonUtils.getValueByPath(json, "name");
String detail = JsonUtils.getValueByPath(json, "detail");
String images = JsonUtils.getValueByPath(json, "images");
String videos = JsonUtils.getValueByPath(json, "videos");
String favoritesId = JsonUtils.getValueByPath(json, "favoritesId");
String price = JsonUtils.getValueByPath(json, "price");
if (StringUtils.isBlank(id)) {
......@@ -133,7 +150,7 @@ public class WxItemController {
return Result.failed("价格不能为空");
}
if (StringUtils.isBlank(images)) {
return Result.failed("图片或视频不能为空");
return Result.failed("图片不能为空");
}
if (StringUtils.isBlank(favoritesId)) {
return Result.failed("收藏册id不能为空");
......@@ -147,6 +164,7 @@ public class WxItemController {
dto.setDetail(detail);
dto.setFavoritesId(Long.parseLong(favoritesId));
dto.setImages(images);
dto.setVideos(videos);
dto.setPrice(price);
return itemService.update(dto);
}
......@@ -223,9 +241,15 @@ public class WxItemController {
return Result.success(map);
}
@ApiOperation(value = "小程序授权码")
@PostMapping("/test")
public Result test() {
return itemService.test();
@ApiOperation(value = "小程序码")
@GetMapping("/getWxacode")
public void getWxacode(String page, String scene, HttpServletResponse response) {
itemService.getWxacode(page, scene, response);
}
@ApiOperation(value = "小程序链接")
@GetMapping("/getWxLink")
public Result getWxLink(String pageUrl) {
return itemService.getWxLink(pageUrl);
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment