国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

微信小程序: java實(shí)現(xiàn)獲取手機(jī)號(hào)方式

這篇具有很好參考價(jià)值的文章主要介紹了微信小程序: java實(shí)現(xiàn)獲取手機(jī)號(hào)方式。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

目錄

1. 現(xiàn)在比較簡(jiǎn)單的方式

-> 接口名

---> 功能描述

-> 調(diào)用方式

---> HTTPS 調(diào)用

---> 第三方調(diào)用

---> 請(qǐng)求參數(shù)

---> 返回參數(shù)

2. 實(shí)現(xiàn)方式

1. 加入fastjson依賴?

2. http請(qǐng)求類

3. Json串工具類

4.接口方法

3.另外介紹一點(diǎn)access_token


1. 現(xiàn)在比較簡(jiǎn)單的方式

微信官方文檔介紹:?

-> 接口名

getPhoneNumber

---> 功能描述

該接口需配合手機(jī)號(hào)快速填寫組件能力一起使用,當(dāng)用戶點(diǎn)擊并同意之后,可以通過?bindgetphonenumber?事件回調(diào)獲取到動(dòng)態(tài)令牌code,再調(diào)用該接口將code換取用戶手機(jī)號(hào)。

注意:每個(gè)code只能使用一次,code的有效期為5min。

-> 調(diào)用方式

---> HTTPS 調(diào)用


POST https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN 

---> 第三方調(diào)用

  • 調(diào)用方式以及出入?yún)⒑虷TTPS相同,僅是調(diào)用的token不同

  • 該接口所屬的權(quán)限集id為:18

  • 服務(wù)商獲得其中之一權(quán)限集授權(quán)后,可通過使用authorizer_access_token代商家進(jìn)行調(diào)用

---> 請(qǐng)求參數(shù)

屬性 類型 必填 說明
access_token string 接口調(diào)用憑證,該參數(shù)為 URL 參數(shù),非 Body 參數(shù)。使用access_token或者authorizer_access_token
code string 手機(jī)號(hào)獲取憑證

---> 返回參數(shù)

屬性 類型 說明
errcode number 錯(cuò)誤碼
errmsg string 錯(cuò)誤信息
phone_info object 用戶手機(jī)號(hào)信息
屬性 類型 說明
phoneNumber string 用戶綁定的手機(jī)號(hào)(國外手機(jī)號(hào)會(huì)有區(qū)號(hào))
purePhoneNumber string 沒有區(qū)號(hào)的手機(jī)號(hào)
countryCode string 區(qū)號(hào)
watermark object 數(shù)據(jù)水印
屬性 類型 說明
timestamp number 用戶獲取手機(jī)號(hào)操作的時(shí)間戳
appid string 小程序appid

2. 實(shí)現(xiàn)方式

1. 加入fastjson依賴?

?       <dependency>
? ? ? ? ? ? <groupId>com.alibaba</groupId>
? ? ? ? ? ? <artifactId>fastjson</artifactId>
? ? ? ? ? ? <version>1.2.75</version>
? ? ? ? </dependency>

2. http請(qǐng)求類

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.MDC;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HTTP/HTTPS 請(qǐng)求封裝: GET / POST
 * 默認(rèn)失敗重試3次
 * @author admin
 */
@Slf4j
public class HttpClientSslUtils {

	/**
	 * 默認(rèn)的字符編碼格式
	 */
	private static final String DEFAULT_CHAR_SET = "UTF-8";
	/**
	 * 默認(rèn)連接超時(shí)時(shí)間 (毫秒)
	 */
	private static final Integer DEFAULT_CONNECTION_TIME_OUT = 2000;
	/**
	 * 默認(rèn)socket超時(shí)時(shí)間 (毫秒)
	 */
	private static final Integer DEFAULT_SOCKET_TIME_OUT = 3000;

	/** socketTimeOut上限 */
	private static final Integer SOCKET_TIME_OUT_UPPER_LIMIT = 10000;

	/** socketTimeOut下限 */
	private static final Integer SOCKET_TIME_OUT_LOWER_LIMIT = 1000;

	private static CloseableHttpClient getHttpClient() {
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(DEFAULT_SOCKET_TIME_OUT)
			.setConnectTimeout(DEFAULT_CONNECTION_TIME_OUT).build();
		return HttpClients.custom().setDefaultRequestConfig(requestConfig)
			.setRetryHandler(new DefaultHttpRequestRetryHandler()).build();
	}

	private static CloseableHttpClient getHttpClient(Integer socketTimeOut) {
		RequestConfig requestConfig =
			RequestConfig.custom().setSocketTimeout(socketTimeOut).setConnectTimeout(DEFAULT_CONNECTION_TIME_OUT)
				.build();
		return HttpClients.custom().setDefaultRequestConfig(requestConfig)
			.setRetryHandler(new DefaultHttpRequestRetryHandler()).build();
	}

	public static String doPost(String url, String requestBody) throws Exception {
		return doPost(url, requestBody, ContentType.APPLICATION_JSON);
	}

	public static String doPost(String url, String requestBody, Integer socketTimeOut) throws Exception {
		return doPost(url, requestBody, ContentType.APPLICATION_JSON, null, socketTimeOut);
	}

	public static String doPost(String url, String requestBody, ContentType contentType) throws Exception {
		return doPost(url, requestBody, contentType, null);
	}

	public static String doPost(String url, String requestBody, List<BasicHeader> headers) throws Exception {
		return doPost(url, requestBody, ContentType.APPLICATION_JSON, headers);
	}

	public static String doPost(String url, String requestBody, ContentType contentType, List<BasicHeader> headers)
		throws Exception {
		return doPost(url, requestBody, contentType, headers, getHttpClient());
	}

	public static String doPost(String url, String requestBody, ContentType contentType, List<BasicHeader> headers,
                                Integer socketTimeOut) throws Exception {
		if (socketTimeOut < SOCKET_TIME_OUT_LOWER_LIMIT || socketTimeOut > SOCKET_TIME_OUT_UPPER_LIMIT) {
			log.error("socketTimeOut非法");
			throw new Exception();
		}
		return doPost(url, requestBody, contentType, headers, getHttpClient(socketTimeOut));
	}


	/**
	 * 通用Post遠(yuǎn)程服務(wù)請(qǐng)求
	 * @param url
	 * 	請(qǐng)求url地址
	 * @param requestBody
	 * 	請(qǐng)求體body
	 * @param contentType
	 * 	內(nèi)容類型
	 * @param headers
	 * 	請(qǐng)求頭
	 * @return String 業(yè)務(wù)自行解析
	 * @throws Exception
	 */
	public static String doPost(String url, String requestBody, ContentType contentType, List<BasicHeader> headers,
                                CloseableHttpClient client) throws Exception {

		// 構(gòu)造http方法,設(shè)置請(qǐng)求和傳輸超時(shí)時(shí)間,重試3次
		CloseableHttpResponse response = null;
		long startTime = System.currentTimeMillis();
		try {
			HttpPost post = new HttpPost(url);
			if (!CollectionUtils.isEmpty(headers)) {
				for (BasicHeader header : headers) {
					post.setHeader(header);
				}
			}
			StringEntity entity =
				new StringEntity(requestBody, ContentType.create(contentType.getMimeType(), DEFAULT_CHAR_SET));
			post.setEntity(entity);
			response = client.execute(post);
			if (response.getStatusLine().getStatusCode() != HttpStatus.OK.value()) {
				log.error("業(yè)務(wù)請(qǐng)求返回失敗:{}", EntityUtils.toString(response.getEntity()));
				throw new Exception();
			}
			String result = EntityUtils.toString(response.getEntity());
			return result;
		} finally {
			releaseResourceAndLog(url, requestBody, response, startTime);
		}
	}

	/**
	 * 暫時(shí)用于智慧園區(qū)業(yè)務(wù)聯(lián)調(diào)方式
	 * @param url 業(yè)務(wù)請(qǐng)求url
	 * @param param 業(yè)務(wù)參數(shù)
	 * @return
	 * @throws Exception
	 */
    public static String doPostWithUrlEncoded(String url,
                                              Map<String, String> param) throws Exception {
        // 創(chuàng)建Httpclient對(duì)象
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = null;
        long startTime = System.currentTimeMillis();
        try {
            // 創(chuàng)建Http Post請(qǐng)求
            HttpPost httpPost = new HttpPost(url);
            // 創(chuàng)建參數(shù)列表
            if (param != null) {
                List<org.apache.http.NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模擬表單
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, DEFAULT_CHAR_SET);
                httpPost.setEntity(entity);
            }
            // 執(zhí)行http請(qǐng)求
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() != HttpStatus.OK.value()) {
				log.error("業(yè)務(wù)請(qǐng)求返回失敗:{}" , EntityUtils.toString(response.getEntity()));
				throw new Exception();
            }
            String resultString = EntityUtils.toString(response.getEntity(), DEFAULT_CHAR_SET);
            return resultString;
        } finally {
            releaseResourceAndLog(url, param == null ? null : param.toString(), response, startTime);
        }
    }

	private static void releaseResourceAndLog(String url, String request, CloseableHttpResponse response, long startTime) {
		if (null != response) {
			try {
				response.close();
				recordInterfaceLog(startTime, url, request);
			} catch (IOException e) {
				log.error(e.getMessage());
			}
		}
	}

	public static String doGet(String url) throws Exception {
		return doGet(url, ContentType.DEFAULT_TEXT);
	}

	public static String doGet(String url, ContentType contentType) throws Exception {
		return doGet(url, contentType, null);
	}

	public static String doGet(String url, List<BasicHeader> headers) throws Exception {
		return doGet(url, ContentType.DEFAULT_TEXT, headers);
	}

	/**
	 * 通用Get遠(yuǎn)程服務(wù)請(qǐng)求
	 * @param url
	 * 	請(qǐng)求參數(shù)
	 * @param contentType
	 * 	請(qǐng)求參數(shù)類型
	 * @param headers
	 * 	請(qǐng)求頭可以填充
	 * @return String 業(yè)務(wù)自行解析數(shù)據(jù)
	 * @throws Exception
	 */
	public static String doGet(String url, ContentType contentType, List<BasicHeader> headers) throws Exception {
		CloseableHttpResponse response = null;
		long startTime = System.currentTimeMillis();
		try {
			CloseableHttpClient client = getHttpClient();
			HttpGet httpGet = new HttpGet(url);
			if (!CollectionUtils.isEmpty(headers)) {
				for (BasicHeader header : headers) {
					httpGet.setHeader(header);
				}
			}
			if(contentType != null){
				httpGet.setHeader("Content-Type", contentType.getMimeType());
			}
			response = client.execute(httpGet);
			if (response.getStatusLine().getStatusCode() != HttpStatus.OK.value()) {
				log.error("業(yè)務(wù)請(qǐng)求返回失敗:{}", EntityUtils.toString(response.getEntity()));
				throw new Exception();
			}
			String result = EntityUtils.toString(response.getEntity());
			return result;
		} finally {
			releaseResourceAndLog(url, null, response, startTime);
		}
	}

	private static void recordInterfaceLog(long startTime, String url, String request) {
		long endTime = System.currentTimeMillis();
		long timeCost = endTime - startTime;
		MDC.put("totalTime", String.valueOf(timeCost));
		MDC.put("url", url);
		MDC.put("logType", "third-platform-service");
		log.info("HttpClientSslUtils 遠(yuǎn)程請(qǐng)求:{} 參數(shù):{} 耗時(shí):{}ms", url, request, timeCost);
	}
}

3. Json串工具類

import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;

@Slf4j
public class JsonUtil {

    /**
     * 定義映射對(duì)象
     */
    public static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 日期格式化
     */
    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    static {
        //對(duì)象的所有字段全部列入
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //取消默認(rèn)轉(zhuǎn)換timestamps形式
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //忽略空Bean轉(zhuǎn)json的錯(cuò)誤
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        //所有的日期格式都統(tǒng)一為以下的樣式,即yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat(DATE_FORMAT));
        //忽略 在json字符串中存在,但是在java對(duì)象中不存在對(duì)應(yīng)屬性的情況。防止錯(cuò)誤
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    }

    /**
     * string轉(zhuǎn)JsonNode
     *
     * @param jsonString
     * @return com.fasterxml.jackson.databind.JsonNode
     */
    public static JsonNode stringToJsonNode(String jsonString) throws JsonProcessingException {

        return objectMapper.readTree(jsonString);

    }

    /**
     * 對(duì)象轉(zhuǎn)json字符串
     *
     * @param obj
     * @param <T>
     */
    public static <T> String objToString(T obj) {

        if (obj == null) {
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.warn("Parse Object to String error : {}", e.getMessage());
            return null;
        }
    }

    /**
     * 對(duì)象轉(zhuǎn)格式化的字符串字符串
     *
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String objToPrettyString(T obj) {
        if (obj == null) {
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.warn("Parse Object to String error : {}", e.getMessage());
            return null;
        }
    }

    /**
     * json字符串轉(zhuǎn)對(duì)象
     *
     * @param jsonString
     * @param cls
     * @param <T>
     */
    public static <T> T stringToObj(String jsonString, Class<T> cls) {
        if (StringUtils.isEmpty(jsonString) || cls == null) {
            return null;
        }
        try {
            return cls.equals(String.class) ? (T) jsonString : objectMapper.readValue(jsonString, cls);
        } catch (JsonProcessingException e) {
            log.warn("Parse String to Object error : {}", e.getMessage());
            return null;
        }
    }

}

4.接口方法

 @PostMapping("/getPhone")
    public ResultResponse getPhone(@RequestBody @Valid WxMiniGetPhone param) {
        JSONObject wxJson;
        // 獲取token
        String token_url = null;

        /**
         * appid切換
         */
        if (param.getWxAppletType() == 1) {
            token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", bAppID, bAppSecret);
        } else if (param.getWxAppletType() == 2) {
            token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", aAppId, aSecret);
        } else {
            throw new UserServiceException("異常");
        }


        try {
            JSONObject token = JSON.parseObject(HttpClientSslUtils.doGet(token_url));
            if (token == null) {
                log.info("獲取token失敗");
                return null;
            }
            String accessToken = token.getString("access_token");
            if (StringUtils.isEmpty(accessToken)) {
                log.info("獲取token失敗");
                return null;
            }
            log.info("token : {}", accessToken);
            //獲取phone
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
                    + "?access_token=" + accessToken;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", param.getCode());
            String reqJsonStr = JsonUtil.objToString(jsonObject);
            wxJson = JSON.parseObject(HttpClientSslUtils.doPost(url, reqJsonStr));

            if (wxJson == null) {
                log.info("獲取手機(jī)號(hào)失敗");
                return ResultResponse.error("獲取手機(jī)號(hào)失敗!");
            }
            return ResultResponse.ok("獲取成功!").setData(wxJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultResponse.error("獲取失敗,請(qǐng)重試!");
    }

3.另外介紹一點(diǎn)access_token

access_token是有次數(shù)限制的 一天2000次 超過了需要刷新accessToken限制次數(shù),10次/月文章來源地址http://www.zghlxwxcb.cn/news/detail-599888.html

到了這里,關(guān)于微信小程序: java實(shí)現(xiàn)獲取手機(jī)號(hào)方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包