java微信小程序后台(支付 授权登陆)

1.微信小程序后台(支付 授权登陆)

1.添加微信依赖(用的是git上面 binarywang包)

<!--支付开发包 -->
<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-pay</artifactId>
    <version>3.8.0</version>
</dependency>
<!-- 小程序 开发包-->
<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-miniapp</artifactId>
    <version>3.8.0</version>
</dependency>

2.相关配置

2.1application.yml配置
wx:
  pay:
    appId: #微信公众号或者小程序等的appid
    mchId: #微信支付商户号
    mchKey: #微信支付商户密钥
    appSecret: #应用密钥
2.2yaml配置参数类
@Data
@Component
@ConfigurationProperties(prefix = "wx.pay")  //前缀
@Primary  //覆盖 当有多个这个的WxPayProperties实现类 注入这个
public class WxPayProperties {
  /**
   * 设置微信公众号或者小程序等的appid
   */
  private String appId;

  /**
   * 微信支付商户号
   */
  private String mchId;

  /**
   * 微信支付商户密钥
   */
  private String mchKey;

  /**
   * 小程序密钥
   */
  private String appSecret;

}
2.3(bean注入 和配置)
/**
 * lijh
 */
@Configuration
@ConditionalOnClass(WxPayService.class) //引入WxPayService这个类 下面两个才会实例化
@EnableConfigurationProperties(WxPayProperties类.class) //注入WxPayProperties类
@AllArgsConstructor 
public class WxPayConfiguration {
    //配置文件类
  private WxPayProperties properties;

  @Bean
  @ConditionalOnMissingBean
  public WxPayService wxService() {
      //实例payConfig 设置固定参数
    WxPayConfig payConfig = new WxPayConfig();
    payConfig.setAppId(StringUtils.trimToNull(this.properties.getAppId()));
    payConfig.setMchId(StringUtils.trimToNull(this.properties.getMchId()));
    payConfig.setMchKey(StringUtils.trimToNull(this.properties.getMchKey()));
    payConfig.setSubAppId(StringUtils.trimToNull(this.properties.getSubAppId()));
    payConfig.setSubMchId(StringUtils.trimToNull(this.properties.getSubMchId()));
    payConfig.setKeyPath(StringUtils.trimToNull(this.properties.getKeyPath()));

    // 可以指定是否使用沙箱环境
    payConfig.setUseSandboxEnv(false);

    WxPayService wxPayService = new WxPayServiceImpl();
    wxPayService.setConfig(payConfig);
    return wxPayService;
  }

  @Bean
  @ConditionalOnMissingBean
  public WxMaService wxMaService() {
      //实例这个 WxMaConfig
    WxMaConfig wxMaConfig = new WxMaDefaultConfigImpl();
    ((WxMaDefaultConfigImpl) wxMaConfig).setAppid(StringUtils.trimToNull(this.properties.getAppId()));
    ((WxMaDefaultConfigImpl) wxMaConfig).setSecret(StringUtils.trimToNull(this.properties.getAppSecret()));
    WxMaService wxMaService = new WxMaServiceImpl();
      //设置配置文件
    wxMaService.setWxMaConfig(wxMaConfig);
    return wxMaService;
  }
}

3.代码实现

3.0 ResponseEntity实体类
/**
 * 返回统一对象
 *
 * @param
 * @return
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class ResponseEntity<T> {
    private Integer code;
    private String message;
    private T data;
    private Long expired_at;


    public static <T> ResponseEntity<T> ok() {
        return restResult(null, SUCCEED_CODE, null);
    }

    public static <T> ResponseEntity<T> ok(String msg) {
        return restResult(null, SUCCEED_CODE, msg);
    }

    public static <T> ResponseEntity<T> ok(T data) {
        return restResult(data, SUCCEED_CODE, null);
    }

    public static <T> ResponseEntity<T> ok(T data, String msg) {
        return restResult(data, SUCCEED_CODE, msg);
    }


    public static <T> ResponseEntity<T> response(ResponseCode responseCode) {
        return restResult(null, responseCode, null);
    }

    public static <T> ResponseEntity<T> response(ResponseCode responseCode, String msg) {
        return restResult(null, responseCode, msg);
    }

    public static <T> ResponseEntity<T> response(ResponseCode responseCode, T data) {
        return restResult(data, responseCode, null);
    }

    public static <T> ResponseEntity<T> response(ResponseCode responseCode, T data, String msg) {
        return restResult(data, responseCode, msg);
    }

    private static <T> ResponseEntity<T> restResult(T data, ResponseCode responseCode, String inputMessage) {
        ResponseEntity<T> responseEntity = new ResponseEntity<>();
        responseEntity.setCode(responseCode.getCode());
        responseEntity.setData(data);
        if (inputMessage == null) {
            responseEntity.setMessage(responseCode.getMessage());
        } else {
            responseEntity.setMessage(inputMessage);
        }
        responseEntity.setExpired_at(System.currentTimeMillis());
        return responseEntity;
    }
}
3.1 获取openId -通过前台生成的code 换取openId
@PostMapping("/code")
public ResponseEntity jsCode2SessionInfo(@RequestBody Map map){
    String code = MapUtils.getString(map, "code");
    if (StringUtils.isEmpty(code)){
        return ResponseEntity.response(ResponseCode.ERROR_CODE).setData("参数错误");
    }
    String result = "";
    try {
        WxMaJscode2SessionResult wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(code);
        result = wxMaJscode2SessionResult.getOpenid();
    } catch (WxErrorException e) {
        e.printStackTrace();
    }
    return ResponseEntity.ok().setData(result);
}
3.2 微信支付 —统一下单
@PostMapping(value = "/wxpay")
    public ResponseEntity pay(HttpServletRequest request, @RequestBody Map map) {
        try {
            String openId = MapUtils.getString(map, "openId");
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setBody("赋强公证");
            //获取日期 流水号
            orderRequest.setOutTradeNo("订单编号");
            //金额
            orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(200));//元转成分
            //openId
            orderRequest.setOpenid(openId);
            //小程序 标识
            orderRequest.setTradeType("JSAPI");
            //数据回馈 地址
            orderRequest.setNotifyUrl(apiConstants.getSynResult());
            //获取ip地址
            InetAddress address = InetAddress.getLocalHost();
            String hostAddress = address.getHostAddress();
            orderRequest.setSpbillCreateIp(hostAddress);
            long currentTime = System.currentTimeMillis() ;
            //交易开始时间
            //设置时差
            TimeZone timeZone = TimeZone.getTimeZone("GMT+8");
            TimeZone.setDefault(timeZone);
            String timeStart = new SimpleDateFormat("yyyyMMddHHmmss").format(currentTime);
            DateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmss");
            orderRequest.setTimeStart(timeStart);
            //交易结束时间
            currentTime +=120*60*1000;
            String timeExpire = format1.format(new Date(currentTime));
            orderRequest.setTimeExpire(timeExpire);
            //订单 返回
            Object order = wxService.createOrder(orderRequest);
            Object json = JSONObject.toJSON(order);
            return ResponseEntity.response(ResponseCode.ERROR_CODE).setData(json);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.response(ResponseCode.ERROR_CODE).setMessage("支付失败,请稍后重试!");
        }
    }
3.3微信支付-授权登陆
/**
     * 获取用户绑定手机号
     * @param map
     * @return
     */
    @PostMapping("/phone")
    public ResponseEntity phone(@RequestBody Map map){
        String code = MapUtils.getString(map, "code");
        if (StringUtils.isEmpty(code)){
            return ResponseEntity.response(RESPONSE_PARAMETER_ERROR,"项目编码不能为空");
        }
        String encryptedData = MapUtils.getString(map, "encryptedData");
        if (StringUtils.isEmpty(encryptedData)){
            return ResponseEntity.response(RESPONSE_PARAMETER_ERROR,"encryptedData不能为空");
        }
        String iv = MapUtils.getString(map, "iv");
        if (StringUtils.isEmpty(iv)){
            return ResponseEntity.response(RESPONSE_PARAMETER_ERROR,"iv不能为空");
        }
        WxMaJscode2SessionResult wxMaJscode2SessionResult = null;
        LoginUserDto loginUserDto = new LoginUserDto();
        ResponseEntity responseEntity = null;
        try {
            //获取session_key
            wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(code);
            if (wxMaJscode2SessionResult == null){
                return ResponseEntity.response(ERROR_CODE,"code信息有误");
            }
            String  session_key = wxMaJscode2SessionResult.getSessionKey();
            //获取联系方式
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(session_key, encryptedData, iv);
            if (phoneNoInfo == null){
                return ResponseEntity.response(ERROR_CODE,"联系方式解密失败");
            }
            //根据联系方式 调用自定义登陆接口
            //String phoneNumber = phoneNoInfo.getPhoneNumber();
            //loginUserDto.setLoginNa(phoneNumber);
            //loginUserDto.setOp("app_wx");
            //调用登陆接口
            //responseEntity = ucUserService.loginUcUser(loginUserDto);
        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseEntity;
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值