【uniapp】小程序开发5:获取openid、获取手机号

一、获取小程序openid

需要配合后端接口获取授权码(code)

1)调用uni.login()方法获取授权code,并把code传给getOpenid

//使用uni.login的时候可以在任何接口下使用即可,主要看打印出来的code值和openid
let that = this
uni.login({
    provider: 'weixin',
    success: function (loginRes) {
      getOpenid(loginRes.code).then(res=>{
    	  console.log('getOpenid',res)
    	  that.openId = res.data.openId
    	  that.userInfo.openId = that.openId
    	  that.$store.commit('setUserInfo', that.userInfo)
      })
    }
});

2)方式一、从后端接口获取openId

从后端接口获取openid

function getOpenid(code) {
	const baseUrl = process.env.VUE_APP_URL;
    return new Promise(function (resolve, reject) {
        let url = baseUrl + '/api/open/weixin/getOauth2Code2Session'
        uni.request({
            url: url,
            data: {
                appId: process.env.VUE_APP_APPID,
                code: code
            },
            method: 'POST',
            success: (res) => {
                console.log('getOauth2Code2Session', res);
                resolve(res)
            }
        })
    })
}

3)方式二、纯前端写法获取openId

function getOpenid(code) {
    return new Promise(function (resolve, reject) {
        let appid = config.appid
        let secret = config.secret
        let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`
        wx.request({
            url: url,
            success: (res) => {
                let openid = res.data.openid;
                // console.log('openid', openid);
                resolve(openid)
            }
        })
    })

}

二、获取手机号

1)增加后端接口获取手机号,类似如下代码

//得到用户手机号
private static final String GET_USER_PHONENUMBER="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
	
/**
 * 得到用户手机号
 * @return
 * @throws WeChatException
 */
public UserPhone getUserPhonenumber(String code) throws WeChatException{
	JSONObject groupJson =new JSONObject();
	groupJson.put("code", code);
	String requestData=groupJson.toString();
	logger.info("request data "+requestData);
	String resultStr = HttpUtils.post(GET_USER_PHONENUMBER+TokenProxy.accessToken(), requestData);
	logger.info("return data "+resultStr);
	WeChatUtil.isSuccess(resultStr);
	return JSONObject.parseObject(resultStr).getObject("phone_info", UserPhone.class);
}

@Data
public class UserPhone {

    private String countryCode;
    private String phoneNumber;
    private String purePhoneNumber;

}

2)增加vue页面文件中增加获取手机号权限代码
open-type="getPhoneNumber"

<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
	style="width: 100%;margin-top: 20px;">
	<text style="width: 100%;font-size: 20px;">点击授权获取手机号text>
button>

3)在vue中增加方法调用后端接口获取手机号

getPhoneNumber(res) {
	console.log('获取用户手机号:', res)
	this.getUserphonenumber(res.detail.code)
},

// 获取手机号
getUserphonenumber(code).then(res2 => {
	let phoneNunber;
	if (res2.data) {
		phoneNunber = res2.data.phoneNumber;
	}
	if (!phoneNunber) {
		wx.showToast({
			title: '没取到手机号',
			icon: 'none'
		})
		return;
	}
	console.log('phoneNumber', phoneNunber)
})

你可能感兴趣的:(前端,uni-app)