Java实现小程序基础开发

Java实现小程序基础开发

描述

继上篇Java整合公众号基本功能实现,现继续完善与公众号管理绑定的小程序功能开发
实现公众号与小程序配套使用
现实现小程序的注册,手机号授权登录,Jsapi授权、小程序与公众号关系

小程序配置类

@Configuration
@RequiredArgsConstructor
@ConditionalOnClass(WxMaService.class)
@EnableConfigurationProperties()
public class WxMaConfiguration {
    private final MiniappConfigMapper miniappConfigMapper;
    /**
     * 默认配置
     */
    private static Map<String, WxMaService> wxMaServices = new HashMap<>();
    /**
     * jsapi配置
     */
    private static Map<String, WxMaJsapiService> WxMaJsapiServices = new HashMap<>();
    /**
     * 用户配置(获取用户客户代码)
     */
    private static Map<String, Integer> MINI_USER_CONF = new HashMap<>();

    public static Map<String, WxMaService> getMpServices() {
        return wxMaServices;
    }

    public static Integer getCustomId(String appid) {
        return MINI_USER_CONF.get(appid);
    }

    public static Map<String, WxMaJsapiService> getWxMaJsapiServices() {
        return WxMaJsapiServices;
    }
    
    /**
     * 小程序多客户
     * @return
     */
    @Bean
    public Object mpServices() {
        List<MiniappConfig> blueWxConfigs = miniappConfigMapper.selectList(Wrappers.emptyWrapper());
        for (MiniappConfig a : blueWxConfigs) {
            WxMaDefaultConfigImpl configStorage = new WxMaDefaultConfigImpl();
            configStorage.setAppid(a.getAppid());
            configStorage.setSecret(a.getSecret());
            configStorage.setToken(a.getToken());
            configStorage.setAesKey(a.getAeskey());
            configStorage.setMsgDataFormat(a.getMsgDataFormat());
            WxMaService service = new WxMaServiceImpl();
            service.setWxMaConfig(configStorage);
            WxMaJsapiService wxMaJsapiService = new WxMaJsapiServiceImpl(service);
            wxMaServices.put(a.getCustomerCode() + ":" + a.getAppid(), service);
            WxMaJsapiServices.put(a.getCustomerCode() + ":" + a.getAppid(), wxMaJsapiService);
            MINI_USER_CONF.put(a.getAppid(), a.getCustomerId());
        }
        return Boolean.TRUE;
    }
}

Jsapi签名

/**
 * 微信小程序获取jsapi签名
 */
@Slf4j
@RestController
@RequestMapping(value = "/miniapp/jsapi",produces = MediaType.APPLICATION_JSON_VALUE)
public class MiniappJsApiController {

	/**
     * 消息处理
     */
    @GetMapping(value = "/{customCode}")
    public WxJsapiSignature authGet(@PathVariable("customCode") String customCode,
                          @RequestParam(name = "url") String url) {
         WxJsapiSignature jsapiSignature = null;
        try {
            log.info("接收到获取接口,customCode=[{}],url=[{}]", customCode, url);
            if (customCode == null || StringUtil.isAnyBlank(url)) {
                log.error("请求参数非法,请核实!");
                return jsapiSignature;
            }
            WxMaJsapiService wxMaJsapiService = WxMaConfiguration.getWxMaJsapiServices().get(customCode);
            if (wxMaJsapiService == null) {
                log.error("没有找到该客户的配置,customCode=[{}]", customCode);
                return jsapiSignature;
            }
            jsapiSignature = wxMaJsapiService.createJsapiSignature(url);
        } catch (Exception e) {
            log.error("WxJsApiController authGet 失败{}", ExceptionUtil.getStackTraceAsString(e));
        }
        return jsapiSignature ;
    }
}

小程序入口

/**
 * 小程序入口
 */
@Slf4j
@RestController
@RequestMapping(value = "/miniapp/portal",produces = MediaType.APPLICATION_JSON_VALUE)
public class MiniappPortalController {

	@GetMapping(value = "/{customCode}", produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable("customCode") String customCode,
                          @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) {
        log.info("\n接收到来自微信服务器的认证消息:signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
                signature, timestamp, nonce, echostr);
                if (StringUtil.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法,请核实!");
        }
        if (customCode == null) {
            customCode = "";
        }
        if (WxMaConfiguration.getMpServices().get(customCode).checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "非法请求";
    }


	@PostMapping(value = "/{customCode}", produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable("customCode") String customCode,
                       @RequestBody String requestBody,
                       @RequestParam("msg_signature") String msgSignature,
                       @RequestParam("encrypt_type") String encryptType,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce) {
        log.info("\n接收微信请求:[msg_signature=[{}], encrypt_type=[{}], signature=[{}]," +
                        " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                msgSignature, encryptType, signature, timestamp, nonce, requestBody);
        if (customCode == null) {
            customCode = "";
        }
        final boolean isJson = Objects.equals(WxMaConfiguration.getMpServices().get(customCode).getWxMaConfig().getMsgDataFormat(),
                WxMaConstants.MsgDataFormat.JSON);
        if (StringUtil.isBlank(encryptType)) {
            // 明文传输的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromJson(requestBody);
            } else {//xml
                inMessage = WxMaMessage.fromXml(requestBody);
            }
            System.out.println(inMessage);
            return "success";
        }
        if ("aes".equals(encryptType)) {
        	WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromEncryptedJson(requestBody, WxMaConfiguration.getMpServices().get(1).getWxMaConfig());
            } else {//xml
                inMessage = WxMaMessage.fromEncryptedXml(requestBody, WxMaConfiguration.getMpServices().get(1).getWxMaConfig(),
                        timestamp, nonce, msgSignature);
            }
            return "success";
        }
        throw new RuntimeException("不可识别的加密类型:" + encryptType);
    }
}

小程序登录

/**
 * 小程序登录入口
 **/
@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping(value = "/miniapp/login", produces = MediaType.APPLICATION_JSON_VALUE)
public class MiniappLoginController {

    /**
     * code登录,只要先拿到微信的sessionKey
     *
     * @param code 微信code
     */
    @ClearAuth
    @GetMapping("/codeLogin")
    public OMiniappLoginVO codeLogin(@RequestParam("code") String code,
                                     @RequestParam(value = "appid", required = false) String appid) {
        OMiniappLoginVO oMiniappLoginVO = new OMiniappLoginVO();
        // 通过code调用微信个人信息接口
        WxMaJscode2SessionResult session = null;
        WxMaService wxMaService = WxMaConfiguration.getMpServices().get(MiniappConstant.PARENT_CODE + ":" + appid);
        session = wxMaService.getUserService().getSessionInfo(code);
        log.info("获取结果为:{}", JSONObject.toJSONString(session));
        String sessionKey = session.getSessionKey();
        //获取微信的openId
        String openId = session.getOpenid();
        //获取微信的unionId,这个和公众号的unionId是一样的,所以可以根据这个来获取公众号用户来确定绑定关系
        String unionId = session.getUnionid();
        Integer customId = WxMaConfiguration.getCustomId(appid);
        //查看是否绑定过
        MiniappUserParent bindUserParent = miniappUserParentMapper.selectOneByOpenId(openId, customId);
        //这个miniappId业务上自行处理,这个主要是记录使用小程序的记录用户,与业务平台的用户一个绑定关系,可以通过这个来关联处理
        Long miniappId = null;
        MpUserParent mpUserParent = mpUserParentMapper.selectOneByUnionId(unionId);
		if (bindUserParent == null) {
            MiniappUserParent miniappUserParent = getMiniappUserParent(unionId, appid);
            miniappUserParent.setOpenId(openId);
            miniappUserParentMapper.insert(miniappUserParent);
            miniappId = miniappUserParent.getMiniappId();
        } else {
            miniappId = bindUserParent.getMiniappId();
        }
        String sessionId = IdUtil.fastSimpleUUID();
		oMiniappLoginVO.setSessionId(sessionId);
        oMiniappLoginVO.setSessionKey(sessionKey);
        return oMiniappLoginVO;
    }


    /**
     * 手机号码授权登录(先调上面的接口,拿到sessionKey)
     *
     * @param iMiniappPhoneLoginVO 机密数据
     * * @param encryptedData  机密数据
     * * @param iv   iv数据
     * * @param appid  
     * @return
     */
    @PostMapping("/phoneLogin.json")
    public void phone(@Valid @RequestBody IPhoneLoginVO iPhoneLoginVO) {
        MiniappUserDTO userDTO = UserUtil.getUser();
        String sessionKey = userDTO.getSessionKey();
        Long miniappId = userDTO.getMiniappId();
        String sessionId = miniappUser.getSessionId();
        String thirdBindingId = iMiniappPhoneLoginVO.getThirdBindingId();
        String appKey = null;
        String encryptedData = iMiniappPhoneLoginVO.getEncryptedData();
        String iv = iMiniappPhoneLoginVO.getIv();
        log.info("encryptedData={},iv={},sessionKey={}", encryptedData, iv, sessionKey);
        String appid = iMiniappPhoneLoginVO.getAppid();
        //获取缓存的数据
        WxMaService wxMaService = WxMaConfiguration.getMpServices().get(MiniappConstant.PARENT_CODE + ":" + appid);
        //解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        log.info("phoneNoInfo数据:{}", phoneNoInfo);
        //获取手机号
        String phone = phoneNoInfo.getPhoneNumber();
        /判断该手机号有没注册过,如果有直接进行一个绑定,没有新增
        AppUserDTO appUserDTO = appUserMapper.selectByPhone(phone);
        if (appUserDTO != null) {
        
        } else {
        
        }
    }
}
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java微信小程序是一种使用Java语言开发微信小程序。在进行Java微信小程序开发之前,首先需要设置微信开发者工具和Java开发环境。 1. 下载并安装微信开发者工具,该工具支持Windows、Mac和Linux操作系统。 2. 配置微信开发者工具,登录微信开放平台开发者账号,并创建一个小程序项目。 3. 下载并安装Java开发环境,包括JDK和开发工具,如Eclipse、IntelliJ IDEA等。 4. 创建一个Java项目,用于开发微信小程序后台逻辑。 5. 在Java项目中使用微信开放平台提供的相关API进行开发,通过接口与小程序前端进行通信。 6. 开发小程序的后台逻辑,包括用户认证、获取用户信息、数据处理等。 7. 部署和测试Java项目,确保后台逻辑能够正确运行。 8. 在微信开发者工具中进行调试和测试,确保小程序前后端的协同工作正常。 Java微信小程序开发教程需要有基本的Java编程知识和熟悉微信开发平台的API。在学习教程时,可以参考官方文档、在线教程和其他开发者分享的经验。学习Java微信小程序开发需要耐心和实践,通过不断的学习和实践来提升自己的开发能力。 ### 回答2: Java微信小程序开发教程是一种指导开发者如何使用Java语言开发微信小程序的教程。微信小程序是一种轻量级的应用程序,可以在微信平台上运行,并且不需要经过下载安装的过程。Java是一种被广泛应用于企业级开发的编程语言,具有很多优势,比如稳定性、安全性和跨平台性。 在Java微信小程序开发教程中,会教授一些基础知识,比如Java语言的语法、面向对象编程的概念和微信小程序的架构。开发者需要了解Java语言的基本语法规则,比如变量、数据类型、运算符和流程控制语句等。同时,还需要学习如何使用Java的面向对象特性来设计和实现微信小程序的功能。 教程还会介绍如何使用Java开发工具,比如Eclipse或IntelliJ IDEA等,来创建和管理微信小程序的项目。开发者需要熟悉这些工具的界面和功能,以便更好地进行开发和调试。 此外,教程还会教授一些关于微信小程序的内容,比如小程序的结构、生命周期和API等。开发者需要了解小程序的页面、组件和事件等基本概念,以及如何利用小程序的API来实现特定的功能,比如获取用户信息、发送消息和支付等。 最后,教程还会提供一些实践案例和示例代码,供开发者参考和学习。通过实际的项目练习,开发者可以更好地理解和掌握Java微信小程序开发技巧和方法。 总之,Java微信小程序开发教程可以帮助开发者快速入门,并提供开发所需的基础知识和实践经验,以便他们能够独立开发和维护微信小程序。 ### 回答3: Java微信小程序开发教程可以分为以下几个步骤: 1. 环境准备:首先,需要电脑上安装JDK(Java Development Kit),并配置好JAVA_HOME环境变量。同时,还需要安装微信小程序开发者工具,用于创建和调试小程序。 2. 创建小程序项目:在微信小程序开发者工具中,选择创建新项目,并填写相应的项目信息,例如项目名称、项目目录等。然后,选择小程序的模板,可以选择Java模板进行开发。 3. 开发页面:使用Java语言来开发小程序的页面。Java微信小程序开发主要采用Spring Boot框架进行开发,可以创建Controller类、Service类和Repository类,进行控制器、服务和数据库操作等相关开发。 4. 编写接口:在Controller类中,编写接口方法用于处理小程序的请求。可以通过注解来标识接口的访问路径和请求方式,然后在方法中编写相应的业务逻辑。 5. 数据库操作:通过Repository类来进行数据库操作,例如增删改查等。可以使用JPA(Java Persistence API)或者MyBatis等框架来简化数据库操作。 6. 前端交互:在小程序页面中,通过Java微信小程序提供的API来实现与后端的交互。可以发送HTTP请求,调用后端接口,并处理返回的数据。 7. 调试与部署:在开发过程中,可以使用微信小程序开发者工具进行实时预览和调试。完成开发后,可以将小程序打包成发布版,然后上传到微信小程序平台进行发布。 以上就是Java微信小程序开发教程的基本步骤。当然,具体的开发过程会涉及到更多的细节和技术,需要在实际开发中进行深入学习和实践。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值