【番外】微信小程序获取开发之获取openId和手机号码

2022-06-08 18:17:13 浏览数 (1)

微信小程序获取开发之获取openId和手机号码

微信官网:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

1、获取code      直接调用API获取code即可,然后将code作为参数传递给接口。

代码语言:javascript复制
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
代码语言:javascript复制
 Page({
	  getPhoneNumber (e) {
		console.log(e.detail.code)
	  }
	})

 此处code就是动态口令,有效期5min。

2、获取openID和手机号码的util类

代码语言:javascript复制
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kunshan.hake.hakekunshanmobilevideoback.Execptions.ErrorCodeException;
import com.kunshan.hake.hakekunshanmobilevideoback.config.YmlConfigUtil;
import com.kunshan.hake.hakekunshanmobilevideoback.model.SessionDTO;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author: Liu Yue
 * @Descripition: 微信操作方法
 * @Date; Create in 2022/6/2 18:14
 **/
@Component
@Slf4j
public class WechatAdapter {

    public static final MediaType JSONType = MediaType.parse("application/json; charset=utf-8");

    private static WechatAdapter wechatAdapter;
    @Resource
    private YmlConfigUtil ymlConfigUtil;

    @PostConstruct
    public void init(){
        wechatAdapter = this;
        wechatAdapter.ymlConfigUtil = this.ymlConfigUtil;
    }
    /**
     * 获取微信新用户的openid
     * @param code
     * @return
     * @throws ErrorCodeException
     */
    public static SessionDTO jscode2session(String code) throws ErrorCodeException {
        String url = wechatAdapter.ymlConfigUtil.getJscode2session_url();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .addHeader("content-type", "application/json")
                .url(String.format(url, wechatAdapter.ymlConfigUtil.getAppid(),
                        wechatAdapter. ymlConfigUtil.getSecret(), code))
                .get()
                .build();
        try {
            Response execute = okHttpClient.newCall(request).execute();
            if (execute.isSuccessful()) {
                SessionDTO sessionDTO = JSON.parseObject(execute.body().string(), SessionDTO.class);
                return sessionDTO;
            } else {
                throw new ErrorCodeException("40091");
            }

        } catch (IOException e) {
            throw new ErrorCodeException("40091");
        }
    }

    /**
     * 获取手机号码
     * 2022年6月3日
     * @param code
     * @return
     * @throws ErrorCodeException
     */
    public static String getUserPhone(String code) throws ErrorCodeException {
        String token_url = wechatAdapter.ymlConfigUtil.getToken_url();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .addHeader("content-type", "application/json")
                .url(String.format(token_url, wechatAdapter.ymlConfigUtil.getAppid(),
                        wechatAdapter. ymlConfigUtil.getSecret()))
                .get()
                .build();
        String getuserphone_url = wechatAdapter.ymlConfigUtil.getGetuserphone_url();
        JSONObject o1 = new JSONObject();
        o1.put("code", code);
        log.info("获取电话号码,第二次请求参数:{}",JSON.toJSONString(o1));
        RequestBody body = RequestBody.create(JSONType,  JSON.toJSONString(o1));

        try {
            Response execute = okHttpClient.newCall(request).execute();
            if (execute.isSuccessful()) {
                String rs1 = execute.body().string();
                log.info("获取电话号码,第一次查询信息:{}",rs1);
                JSONObject jsonObject = JSON.parseObject(rs1);
                String access_token = (String)jsonObject.get("access_token");

                Request request2 = new Request.Builder()
                        .addHeader("content-type", "application/json")
                        .url(String.format(getuserphone_url, access_token))
                        .post(body)
                        .build();
                execute = okHttpClient.newCall(request2).execute();
                if (execute.isSuccessful()) {
                    String rs2 = execute.body().string();
                    log.info("获取电话号码,第二次查询信息:{}",rs2);
                    jsonObject = JSON.parseObject(rs2);
                    JSONObject data3 = (JSONObject)jsonObject.get("phone_info");
                    return (String) data3.get("phoneNumber");
                }else {
                    log.error("获取电话号码,第二次查询信息失败");
                    throw new ErrorCodeException("50093");
                }
            } else {
                log.error("获取电话号码,第一次查询信息失败");
                throw new ErrorCodeException("50091");
            }

        } catch (IOException e) {
            throw new ErrorCodeException("50092");
        }
    }
}

其他的辅助类

代码语言:javascript复制
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;

/**
 * @Author: Liu Yue
 * @Descripition: 微信用户
 * @Date; Create in 2022/6/2 18:15
 **/
@Data
public class SessionDTO {

    private String openid;

    @JSONField(name = "session_key")
    private String sessionKey;

}

maven 引用

代码语言:javascript复制
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.7.2</version>
        </dependency>

yml配置

代码语言:javascript复制
wechat:
  jscode2session_url:  https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code
  appid: wxxxxxxxxxxxxxx                   #试用版本
  secret: 2axxxxxxxxxxxxx    #试用版本
  token_url: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s
  getuserphone_url: https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s

其他service层和controller层,自行补全。

0 人点赞