微信授权绑定账号&推送模板消息
使用公众号测试平台开发
https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
https://github.com/wechat-group/weixin-java-tools
微信框架介绍
maven依赖
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.10</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>2.8.0</version>
</dependency>
配置文件
logging:
level:
org.springframework.web: DEBUG
com.github.binarywang.demo.wechat: DEBUG
wechat:
mp:
appId: wx5c43fde3c9733d9e
secret: b8b217126c33a5fb7074927d5e72a81a
token: newbies
aesKey:
微信环境搭建
服务器通知验签
@Slf4j
@RestController
@RequestMapping("/weixin/dispatcherServlet")
public class WeiXinDispatcherServlet {
@Autowired
private WxMpService wxService;
@Autowired
private WxMpMessageRouter router;
/**
* 时间通知验证
*
* @param signature
* @param timestamp
* @param nonce
* @param echostr
* @return
*/
@GetMapping(produces = "text/plain;charset=utf-8")
public String authGet(@RequestParam(name = "signature", required = false) String signature,
@RequestParam(name = "timestamp", required = false) String timestamp,
@RequestParam(name = "nonce", required = false) String nonce,
@RequestParam(name = "echostr", required = false) String echostr) {
this.log.info("\n接收到来自微信服务器的认证消息:[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);
if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
throw new IllegalArgumentException("请求参数非法,请核实!");
}
if (this.wxService.checkSignature(timestamp, nonce, signature)) {
return echostr;
}
return "非法请求";
}
private WxMpXmlOutMessage route(WxMpXmlMessage message) {
try {
return this.router.route(message);
} catch (Exception e) {
this.log.error(e.getMessage(), e);
}
return null;
}
}
QQ授权登录和微信框架jar冲突怎么解决
在不同jar中,有相同的包名和类怎么解决冲突问题
①使用继承方式
②使用java反编译修改源码
微信绑定账户&推送用户
步骤:
- 微信授权成功后,获取授权用户openId,保存在数据库中
- 用户下单支付成功后,查找对应用户openid,调用消息服务平台进行推送微信消息
- 消息服务平台调用微信接口,进行推送消息
会员服务接口
Controller
/**
*
* @methodDesc: 功能描述:(使用openid查找用户信息)
* @param: @param
* token
* @param: @return
*/
@PostMapping("/findWeiXinOpenId")
public Map<String, Object> findWeiXinOpenId(@RequestParam("openid") String openid);
/**
*
* @methodDesc: 功能描述:(使用token查找用户信息)
* @param: @param
* token
* @param: @return
*/
@PostMapping("/getUserId")
public Map<String, Object> getUserId(@RequestParam("userId") Long userId);
Service
@Override
public Map<String, Object> findWeiXinOpenId(String openid) {
UserEntity userEntity = userDao.findWeiXinOpenId(openid);
if (userEntity == null) {
return setResutError("没有查找到该信息.");
}
// 自动登录
String token = setLoginToken(userEntity.getId());
return setResutSuccessData(token);
}
@Override
public Map<String, Object> getUserId(Long userId) {
UserEntity userInfo = userDao.getUserInfo(userId);
if (userInfo == null) {
return setResutError("没有查找到该信息.");
}
return setResutSuccessData(userInfo);
}
Dao
@Mapper
public interface UserDao extends BaseDao {
@Select("select ID,USERNAME,PASSWORD,phone,EMAIL, created,updated from mb_user WHERE PHONE=#{phone} and password=#{password}")
public UserEntity getUserPhoneAndPwd(@Param("phone") String userName, @Param("password") String password);
@Select("select ID,USERNAME,PASSWORD,phone,EMAIL, created,updated,openId,weixinOpenId from mb_user WHERE id=#{id}")
public UserEntity getUserInfo(@Param("id") Long id);
@Select("select ID,USERNAME,PASSWORD,phone,EMAIL, created,updated ,openId,weixinOpenId from mb_user WHERE openid=#{openid}")
public UserEntity findOpenId(@Param("openid") String openid);
@Select("select ID,USERNAME,PASSWORD,phone,EMAIL, created,updated ,openId,weixinOpenId from mb_user WHERE weixinOpenId=#{openid}")
public UserEntity findWeiXinOpenId(@Param("openid") String openid);
}
Web系统系统
数据库中 新增weixinopenid字段
创建com.newbies.weixin.controller包名
@Controller
public class WeChatController {
private static final String ERROR = "error";
private static final String INDEX = "index";
private static final String ASSOCIATEDACCOUNT = "associatedAccount";
@Autowired
private WxMpService wxService;
@Autowired
private UserFeign userFeign;
/**
* 微信授权回调
*
* @return
* @throws WxErrorException
*/
@RequestMapping("/weixinCallback")
public String callback(String code, HttpSession httpSession, HttpServletResponse response) throws WxErrorException {
// 第二步:通过code换取网页授权access_token
WxMpOAuth2AccessToken oauth2getAccessToken = wxService.oauth2getAccessToken(code);
WxMpUser oauth2getUserInfo = wxService.oauth2getUserInfo(oauth2getAccessToken, "zh_CN");
c
}
}
创建微信服务
项目名称Newbies-Shopp-Weixin-Api
WeiXinServiceImpl
@Slf4j
@RequestMapping("/weiXin")
@RestController
public class WeiXinServiceImpl implements WeiXinService {
@Autowired
private WxMpService wxService;
@RequestMapping("/sendTemplate")
public String sendTemplate(@RequestBody WxMpTemplateMessage wxMpTemplateMessage) {
WxMpTemplateMsgService templateMsgService = wxService.getTemplateMsgService();
try {
return templateMsgService.sendTemplateMsg(wxMpTemplateMessage);
} catch (Exception e) {
log.error("WeiXinServiceImpl### ERROR:", e);
return null;
}
}
}
推送报文
{
"toUser": "okYSmtzp4wWCrDCncMfGSRECVSeM",
"templateId": "BHK-47yEvBqHMU-diEIbAQCCuC8H3lsAv-J5rrwyyTc",
"url": "http://www.newbies.com",
"data": [
{
"name": "first",
"value": "2017年11月06日 23:32",
"color": "#173177"
},
{
"name": "keyword1",
"value": "30",
"color": "#173177"
},
{
"name": "keyword2",
"value": "201410515111522",
"color": "#173177"
}
]
}
支付回调改造
// mq推送支付成功消息
Double price = (double) (paymentInfo.getPrice() / 100);
String mqWeiXinJson = weixinMessage(paymentInfo.getUserId(), paymentInfo.getOrderId(), price);
// 队列
Destination activeMQQueue = new ActiveMQQueue(MESSAGES_QUEUE);
log.info("###asyn() 支付发微信推送报文mqWeiXinJson:{}", mqWeiXinJson);
// mq
registerMailboxProducer.send(activeMQQueue, mqWeiXinJson);
RegisterMailboxProducer
@Service("registerMailboxProducer")
public class RegisterMailboxProducer {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate ;
public void send(Destination destination,String json){
jmsMessagingTemplate.convertAndSend(destination, json);
}
}
配置信息
##activemq连接信息
activemq:
broker-url: tcp://localhost:61616
in-memory: true
pool:
enabled: false
##队列
messages:
queue: mail_queue
消息中间件
@Slf4j
@Service
public class WeiXinMQService implements MessageAdapter {
@Autowired
private UserFeign userFeign;
@Autowired
private WeiXinFeign weiXinFeign;
@Override
public void distribute(JSONObject jsonObject) {
Long userId = jsonObject.getLong("userId");
Map<String, Object> resultMap = userFeign.getUserId(userId);
Integer code = (Integer) resultMap.get(BaseApiConstants.HTTP_CODE_NAME);
if (code.equals(BaseApiConstants.HTTP_200_CODE)) {
Map<String, Object> mapItem = (Map<String, Object>) resultMap.get("data");
String json = new JSONObject().toJSONString(mapItem);
UserEntity userEntity = new JSONObject().parseObject(json, UserEntity.class);
String weixinOpenId = userEntity.getWeixinOpenId();
if (StringUtils.isEmpty(weixinOpenId)) {
log.error("distribute() weixinOpenId is null ");
return;
}
// 调用微信接口
WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
wxMpTemplateMessage.setToUser(weixinOpenId);
wxMpTemplateMessage.setUrl("http://www.newbies");
wxMpTemplateMessage.setTemplateId("BHK-47yEvBqHMU-diEIbAQCCuC8H3lsAv-J5rrwyyTc");
List<WxMpTemplateData> data = new ArrayList<>();
// 设置时间
WxMpTemplateData wxMpTemplateData1 = new WxMpTemplateData();
wxMpTemplateData1.setName("first");
wxMpTemplateData1.setValue(DateUtils.currentFormatDate(DateUtils.DATE_TO_STRING_DETAIAL_PATTERN));
wxMpTemplateData1.setColor("#173177");
// 时间价格
WxMpTemplateData wxMpTemplateData2 = new WxMpTemplateData();
wxMpTemplateData2.setName("keyword1");
Double price = jsonObject.getDouble("price");
wxMpTemplateData2.setValue(price + "");
wxMpTemplateData2.setColor("#173177");
// 设置订单号
WxMpTemplateData wxMpTemplateData3 = new WxMpTemplateData();
wxMpTemplateData3.setName("keyword2");
String orderId = jsonObject.getString("orderId");
wxMpTemplateData3.setValue(orderId);
wxMpTemplateData3.setColor("#173177");
data.add(wxMpTemplateData1);
data.add(wxMpTemplateData2);
data.add(wxMpTemplateData3);
wxMpTemplateMessage.setData(data);
weiXinFeign.sendTemplate(wxMpTemplateMessage);
}
}
}
常用接口
网页授权
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5c43fde3c9733d9e&redirect_uri=http%3a%2f%2fyanggaige.tunnel.qydev.com%2fdispatCherServlet&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
获取用户access_token接口
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
获取用户信息接口
https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
创建消息模板接口
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=euQvaT-6C7nMkttXxtzqA9r3yp0MX--ME7-37EbNsA9rVKgzhLvLgVgJIEw2fIJk0W84ShQcLEYUfgsSpgXpwk_6ABiuVfAh5CeN7UF_oAELCmWc0cMy2qsBZI8Ul6orNWIjAEAGPB
{
"touser": "okYSmtzp4wWCrDCncMfGSRECVSeM",
"template_id": "BHK-47yEvBqHMU-diEIbAQCCuC8H3lsAv-J5rrwyyTc",
"url": "http://www.newbies.com",
"topcolor": "#FF0000",
"data": {
"first": {
"value": "2017年11月06日 23:32",
"color": "#173177"
},
"keyword1": {
"value": "30",
"color": "#173177"
},
"keyword2": {
"value": "201410515111522",
"color": "#173177"
}
}
}
|