Spring Boot

微信开发中常用的操作

微信扫一扫,分享到朋友圈

微信开发中常用的操作
收藏 0 0

基于SpringBoot 项目

pom.xml 添加依赖

<!--微信-->
<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-miniapp</artifactId>
    <version>3.3.0</version>
</dependency>
<!--微信支付-->
<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-pay</artifactId>
    <version>3.3.0</version>
</dependency>

1、根据code获取openid

WxProperties 类

import org.springframework.context.annotation.Configuration;

@Configuration

public class WxProperties {

 
    private String appId="APPID";
    

    private String appSecret="APPSECRET";

    private String mchId="商户号";

    private String mchKey="支付秘钥";

    private String notifyUrl="支付回调";
    
    private String keyPath="支付证书绝对路径";

    public String getNotifyUrl() {
        return notifyUrl;
    }

    public void setNotifyUrl(String notifyUrl) {
        this.notifyUrl = notifyUrl;
    }

    public String getMchKey() {
        return mchKey;
    }

    public void setMchKey(String mchKey) {
        this.mchKey = mchKey;
    }

    public String getAppId() {
        return this.appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getAppSecret() {
        return appSecret;
    }

    public void setAppSecret(String appSecret) {
        this.appSecret = appSecret;
    }

    public String getMchId() {
        return mchId;
    }

    public void setMchId(String mchId) {
        this.mchId = mchId;
    }

    public String getKeyPath() {
        return keyPath;
    }

    public void setKeyPath(String keyPath) {
        this.keyPath = keyPath;
    }
}

WxConfig类


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WxConfig {
    @Autowired
    private WxProperties properties;

    @Bean
    public WxMaConfig wxMaConfig() {
        WxMaInMemoryConfig config = new WxMaInMemoryConfig();
        config.setAppid(properties.getAppId());
        config.setSecret(properties.getAppSecret());
        return config;
    }


    @Bean
    public WxMaService wxMaService(WxMaConfig maConfig) {
        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(maConfig);
        return service;
    }

    @Bean
    public WxPayConfig wxPayConfig() {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(properties.getAppId());
        payConfig.setMchId(properties.getMchId());
        payConfig.setMchKey(properties.getMchKey());
        payConfig.setNotifyUrl(properties.getNotifyUrl());
        payConfig.setKeyPath(properties.getKeyPath());
        payConfig.setTradeType("JSAPI");
        payConfig.setSignType("MD5");
        return payConfig;
    }

    @Bean
    public WxPayService wxPayService(WxPayConfig payConfig) {
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }
}

Controller 类

 @Resource
 private WxMaService wxService;



  WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);

  //session_key  
  //openid
  //unionid     开发者才有一般用户没有
  
  String accessToken = this.wxService.getAccessToken();
  
  //accessToken  

微信支付

 @Resource
 private WxPayService wxPayService;

方法:

 WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();

orderRequest.setOutTradeNo(id);
                orderRequest.setOpenid("ID");
                orderRequest.setBody("订单:" + ID);
                orderRequest.setTotalFee("金额转成分");
                orderRequest.setSpbillCreateIp("IP");
                orderRequest.setNotifyUrl("回调地址");

//可以动态更换微信商户

WxPayConfig config=wxPayService.getConfig();
                    config.setAppId("");
                    config.setMchId("");
                    config.setMchKey(");
                    wxPayService.setConfig(config);
//统一下单
 result = wxPayService.createOrder(orderRequest);
                System.out.println(orderRequest.toString());
                System.out.println(result.toString());

支付回调

@RequestMapping("/selectOrder")
    @ResponseBody
    @ApiOperation("订单查询")
    public String selectOrder(HttpServletRequest req, HttpServletResponse resp, @RequestBody String body) {
        WxPayOrderNotifyResult result = null;
        try {
            System.out.println("X=:" + body);
            result = wxPayService.parseOrderNotifyResult(body);


            // 结果正确 outTradeNo
            String orderId = result.getOutTradeNo();
            String tradeNo = result.getTransactionId();
            String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());

            System.out.println("交易单号:" + result.getTransactionId());
            System.out.println("订单号:" + result.getOutTradeNo());
            System.out.println("付款金额:" + BaseWxPayResult.fenToYuan(result.getTotalFee()));

            if ("SUCCESS".equals(result.getResultCode())) {
                System.out.println("支付回调进来了:付款成功");
           
              return "SUCCESS";
            } else {
                System.out.println("支付回调进来了:付款失败");
            }
        } catch (Exception e) {
            log.error("商品支付报错了");
            e.printStackTrace();
        }
SendWxMessageController   微信消息模板推送
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lhym.applet.config.WxProperties;
import com.lhym.applet.utils.utils.DateUtil;
import com.lhym.applet.utils.utils.TemplateData;
import com.lhym.applet.utils.utils.WxMssVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
public class SendWxMessageController {

    @Autowired
    private WxProperties wxProperties;

    /*
     * 发送订阅消息
     * */
    @GetMapping("/pushOneUser")
    public String pushOneUser() {
        return push("ovx3Q4jBjgZcQRAI7ekp4Fu_j56I");
    }

    public String push(String openid) {
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token(时间开发中,应该在access_token快过期时再重新获取)
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户的openid(要发送给那个用户,通常这里应该动态传进来的)
        wxMssVo.setTemplate_id("Fr1mOUoIqtaF80NxhVeOBS1YAxufFGQ79y_qVi5Zhew");//订阅消息模板id
        wxMssVo.setPage("pages/start/start");

        Map<String, TemplateData> m = new HashMap<>(3);
        m.put("character_string2", new TemplateData("123456789"));
        m.put("amount3", new TemplateData("598"));
        m.put("date4", new TemplateData(DateUtil.getDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYY年MM月DD日)));
        m.put("thing5", new TemplateData("西决下单啦"));
        m.put("thing6", new TemplateData("焕彩素颜霜"));

        wxMssVo.setData(m);
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        return responseEntity.getBody();
    }


    @GetMapping("/getAccessToken")
    public String getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", wxProperties.getAppId());  //
        params.put("APPSECRET", wxProperties.getAppSecret());  //
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String Access_Token = object.getString("access_token");
        String expires_in = object.getString("expires_in");
        System.out.println("有效时长expires_in:" + expires_in);
        return Access_Token;
    }
}

工具类

WxMssVo
import java.util.Map;

public class WxMssVo {
    private String touser;//用户openid
    private String template_id;//订阅消息模版id
    private String page = "pages/index/index";//默认跳到小程序首页
    private Map<String, TemplateData> data;//推送文字

    public String getTouser() {
        return touser;
    }

    public void setTouser(String touser) {
        this.touser = touser;
    }

    public String getTemplate_id() {
        return template_id;
    }

    public void setTemplate_id(String template_id) {
        this.template_id = template_id;
    }

    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

    public Map<String, TemplateData> getData() {
        return data;
    }

    public void setData(Map<String, TemplateData> data) {
        this.data = data;
    }
}

TemplateData

public class TemplateData {
    private String value;//

    public TemplateData(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}
展开阅读全文
干一件事情,用心干就完了
下一篇

MQTT 限制匿名用户访问,开启用户密码认证

你也可能喜欢

发表评论

您的电子邮件地址不会被公开。 必填项已用 * 标注

提示:点击验证后方可评论!

插入图片

分类目录

微信扫一扫

微信扫一扫