微信小程序获取手机号(Java后端)

本文介绍了作者在开发微信小程序时,通过调用微信API获取用户手机号的过程,包括获取access_token的步骤以及使用code获取手机号的方法,最后提到了code的有效期问题。
摘要由CSDN通过智能技术生成

最近在做小程序后端的时候,需要拿到手机号进行角色校验,小白也是第一次获取小程序的手机号,所以功能完毕后总结一下本次操作咯。

根据微信小程序官方文档:获取手机号 | 微信开放文档

调用的接口是getPhoneNumber

 请求参数

 从伤处请求参数来看,我们要获取手机号,先得拿到该接口所需参数access_token。

下面看看如何拿到access_token?

看看文档

文档只有一点点啊,根本看不出来如何请求,后来看了网上的一些教程,才知道获取access_token又需要调一个接口

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s

参数:微信小程序的appIdappSecret

先根据appId,appSecret调用接口获取到access_token

//通过appid和secret来获取token
String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId, appSecret);
String accessToken = String.valueOf(JSON.parseObject(HttpUtil.get(tokenUrl)).get("access_token"));

然后再根据access_token,和前端生成的code来获取用户手机号就OK了。

 

//通过token和code来获取用户手机号
String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken + "&code=" + code;

Map<String, String> paramMap = new HashMap<>();
paramMap.put("code", code);
HttpHeaders headers = new HttpHeaders();
HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);
String body = String.valueOf(response.getBody());// 解析JSON字符串
log.info(body);
// 定义一个正则表达式来匹配 phoneNumber
Pattern pattern = Pattern.compile("phoneNumber=(\\d+)");
Matcher matcher = pattern.matcher(body);
if (matcher.find()) {
    String phoneNumber = matcher.group(1); // 获取括号中的数字
    log.info("phoneNumber:" + phoneNumber);
    return AjaxResult.success(phoneNumber);
} else {
    return AjaxResult.error("手机号获取失败!");
}

注意:前端生成的code5分钟就过期了

下面附上完整的接口代码吧!!!!!!!!

由于这个controller里还有其他接口,所以这里把包和代码分开了。大概有个参考!

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.cvit.applet.Enum.AppletConstants;
import com.cvit.applet.domain.StorageAccount;
import com.cvit.applet.mapper.AccountMapper;
import com.cvit.framework.core.domain.AjaxResult;
import com.cvit.framework.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

接口代码: 

    @Value("${weixin.appId}")
    private String appId;

    @Value("${weixin.appSecret}")
    private String appSecret;

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/login")
    public AjaxResult login(String code) {
        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("手机号获取凭证不能为空!");
        }
        //通过appid和secret来获取token
        String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId, appSecret);
        String accessToken = String.valueOf(JSON.parseObject(HttpUtil.get(tokenUrl)).get("access_token"));
        log.info(accessToken);

        //通过token和code来获取用户手机号
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken + "&code=" + code;

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", code);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);
        String body = String.valueOf(response.getBody());// 解析JSON字符串
        log.info(body);
        // 定义一个正则表达式来匹配 phoneNumber
        Pattern pattern = Pattern.compile("phoneNumber=(\\d+)");
        Matcher matcher = pattern.matcher(body);
        if (matcher.find()) {
            String phoneNumber = matcher.group(1); // 获取括号中的数字
            log.info("phoneNumber:" + phoneNumber);
            return AjaxResult.success(phoneNumber);
        } else {
            return AjaxResult.error("手机号获取失败!");
        }
    }

 

好了,大概可能估计也许就这些了,有想法的老师请多指点。。。。。。。。

 

  • 15
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要将微信小程序中的图片传到Java后端,可以采用如下步骤: 1. 在小程序中选择需要上传的图片,并将其转换为base64编码格式。 2. 通过微信小程序API将base64编码的图片数据传输到后端服务器。 3. 在Java后端中接收base64编码的图片数据,并将其转换为图片文件。 4. 将转换后的图片文件存储到服务器本地或云存储中。 以下是一个简单的Java代码示例,用于将base64编码的图片数据转换为图片文件并上传到服务器: ``` import java.io.*; public class Base64ImageDecoder { public static void decode(String base64ImageString, String outputPath) { try { byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64ImageString); InputStream in = new ByteArrayInputStream(imageBytes); BufferedImage image = ImageIO.read(in); ImageIO.write(image, "jpg", new File(outputPath)); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述示例中,`decode`方法接收两个参数:base64编码的图片数据和图片文件输出路径。该方法会先将base64编码的图片数据解码为二进制数据,然后使用Java的`ImageIO`类将二进制数据转换为图片文件,并将其保存到指定的输出路径中。 在实际应用中,你需要将该代码集成到你的Java后端服务中,并根据具体的业务逻辑进行调用。同时,你还需要根据你的系统环境和需求选择适合的图片存储方式,例如使用本地文件系统或云存储服务。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值