如果您对小程序通过用户授权获取手机号之getPhoneNumber感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于小程序通过用户授权获取手机号之getPhoneNumber的
如果您对小程序通过用户授权获取手机号之getPhoneNumber感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于小程序通过用户授权获取手机号之getPhoneNumber的详细内容,我们还将为您解答小程序授权获取用户的信息和手机号的相关问题,并且为您提供关于android – 导入com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder类未找到、JAVA微信公众号网页开发 —— 用户授权获取openid和用户微信信息、PHP配合微信小程序实现获取手机号码详解、Python(phone)模块获取手机号归属地、区号、运营商等的有价值信息。
本文目录一览:- 小程序通过用户授权获取手机号之getPhoneNumber(小程序授权获取用户的信息和手机号)
- android – 导入com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder类未找到
- JAVA微信公众号网页开发 —— 用户授权获取openid和用户微信信息
- PHP配合微信小程序实现获取手机号码详解
- Python(phone)模块获取手机号归属地、区号、运营商等
小程序通过用户授权获取手机号之getPhoneNumber(小程序授权获取用户的信息和手机号)
小程序有一个获取用户很便捷的api,就是通过getPhoneNumber获取用户的已经绑定微信的手机号码。有一点要大家注意,现在微信和注重用户体验,有些方法都是需要用户主动去触发才能调用的,比如getPhoneNumber。
官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
实现思路:
直接上干货:
<button open-type="getPhoneNumber"bindgetPhoneNumber"getPhoneNumber"></button>
JS内getPhoneNumbe组件函数(该事件中最重要的就是在wx.login登录后发起接口请求),这里需要配置参数来给接口: 这些是必不可少的参数,这些齐备才能算一个合法的请求。
最终结果展示:
点击"拒绝",开发者能捕捉到该事件 ,此时getPhoneNumber 函数返回 e.detail.errMsg 为 getPhoneNumber:user deny
android – 导入com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder类未找到
PhoneNumberOfflineGeocoder应该这样做,它的getCountryNameForNumber(PhoneNumber编号,Locale语言)方法应该这样做.但我无法弄清楚如何正确导入该类.
解决方法
JAVA微信公众号网页开发 —— 用户授权获取openid和用户微信信息
官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
HttpClientUtil.java
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
private static class SingletonHolder{
private final static HttpClientUtil INSTANCE=new HttpClientUtil();
}
private HttpClientUtil(){}
public static HttpClientUtil getInstance(){
return SingletonHolder.INSTANCE;
}
public String get(String url){
CharsetHandler handler = new CharsetHandler("UTF-8");
CloseableHttpClient client = null;
try {
HttpGet httpget = new HttpGet(new URI(url));
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
client= httpClientBuilder.build();
client = (CloseableHttpClient) wrapClient(client);
return client.execute(httpget, handler);
} catch (Exception e) {
//e.printStackTrace();
return "";
}finally {
try {
if(client!=null){
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String post(String url, String params,String contentType)
{
//创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//HttpClient
CloseableHttpClient client = httpClientBuilder.build();
client = (CloseableHttpClient) wrapClient(client);
HttpPost post = new HttpPost(url);
CloseableHttpResponse res = null;
try
{
StringEntity s = new StringEntity(params,"UTF-8");
if(StringUtils.isBlank(contentType)){
s.setContentType("application/json");
}
s.setContentType(contentType);
s.setContentEncoding("utf-8");
post.setEntity(s);
res = client.execute(post);
HttpEntity entity = res.getEntity();
return EntityUtils.toString(entity, "utf-8");
}
catch (Exception e)
{
e.printStackTrace();
} finally {
try {
res.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
public static String post(String urlStr,String xmlInfo) {
String line1 = "";
try {
URL url = new URL(urlStr);
URLConnection con = url.openConnection();
con.setDoOutput(true);
//con.setRequestProperty("Pragma:", "no-cache");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "text/xml");
OutputStreamWriter out = new OutputStreamWriter(con
.getOutputStream());
out.write(new String(xmlInfo.getBytes("utf-8")));
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(con
.getInputStream()));
String line = "";
for (line = br.readLine(); line != null; line = br.readLine()) {
line1+=line;
}
return new String(line1.getBytes(),"utf-8");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private class CharsetHandler implements ResponseHandler<String> {
private String charset;
public CharsetHandler(String charset) {
this.charset = charset;
}
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
if (!StringUtils.isBlank(charset)) {
return EntityUtils.toString(entity, charset);
} else {
return EntityUtils.toString(entity);
}
} else {
return null;
}
}
}
private static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLSv1");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
} catch (Exception ex) {
return null;
}
}
}
(注:获取到的code只能使用一次,每次请求都要重新获取一次code,因此以下方法,如果用户重新刷新了页面,就会报错,建议把使用过的code放在缓存中,每次请求接口前判断code是否已经使用,如果使用了就重新获取code去请求接口)
MessageAct.java
package com.test;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class MessageAct {
private String appid="公众号的APP_ID";
private String secret="公众号的APP_SECRET";
/**
* 微信登录
*
* @param code
* @param redirectUrl 返回用户的登录地址
* @param request
* @param response
* @param model
* @return
* @throws IOException
*/
@RequestMapping(value = "/weixinLogin")
public String weixinLogin(String code, String redirectUrl, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
String redirect_uri = "该网站服务的域名地址"+request.getRequestURI(); //该回调地址就是当前方法的URL,需外网能够访问
//-----在这里判断code是否已经存在于缓存中,如果存在,说明code已经使用过,需要重新获取code------
//获取code
if (StringUtils.isBlank(code)) {
try {
PrintWriter out = response.getWriter();
out.println("<script>window.location.href=''" + getCodeUrl(redirect_uri) + "''</script>");
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
String[] s = getOpenId(code);
String openId = s[0];
String accessToken = s[1];
String[] userInfo = getUserInfo(openId, accessToken);//获取用户信息
System.out.println("手机登录openId=================================>" + openId);
User user = userMng.findById(openId); //查询用户是否存在,openId 作为查询条件
if (user != null) {
//用户已经存在
return redirectUrl;
} else {
//用户不存在,进行注册操作
}
}
/**
* 获取用户授权 得到openId,accessToken
*
* @param code
* @return
*/
public String[] getOpenId(String code) {
String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code";
tokenUrl = tokenUrl + "&appid=" + appid + "&secret=" + secret + "&code=" + code;
JSONObject json = null;
try {
json = new JSONObject(HttpClientUtil.getInstance().get(tokenUrl));
//------------在这里把使用过的code存入到缓存中--------
} catch (JSONException e2) {
e2.printStackTrace();
}
String openId = "";
String accessToken = "";
String[] s = new String[2];
if (json != null) {
try {
openId = json.getString("openid");
accessToken = json.getString("access_token");
s[0] = openId;
s[1] = accessToken;
} catch (JSONException e) {
String errcode = null;
try {
errcode = json.getString("errcode");
System.out.println("errcode================>手机登录 获取用户授权失败" + errcode);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
return s;
}
/**
* 获取用户信息 拉取用户信息(需scope为 snsapi_userinfo)
* 只有在用户将公众号绑定到微信开放平台帐号后,可以获取unionid
*
* @param
* @param
* @return
*/
public String[] getUserInfo(String openid, String accessToken) {
String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?lang=zh_CN";
userInfoUrl = userInfoUrl + "&access_token=" + accessToken + "&openid=" + openid;
JSONObject json = null;
try {
json = new JSONObject(HttpClientUtil.getInstance().get(userInfoUrl));
} catch (JSONException e2) {
e2.printStackTrace();
}
String nickname = ""; //用户昵称
String sex = ""; //用户的性别
String province = ""; //用户个人资料填写的省份
String city = ""; //普通用户个人资料填写的城市
String country = ""; //国家,如中国为CN
String headimgurl = ""; //用户头像,
String unionid = ""; //
String[] s = new String[6];
if (json != null) {
try {
nickname = json.getString("nickname");
sex = json.getString("sex");
province = json.getString("province");
city = json.getString("city");
country = json.getString("country");
headimgurl = json.getString("headimgurl");
s[0] = nickname;
s[1] = sex;
s[2] = province;
s[3] = city;
s[4] = country;
s[5] = headimgurl;
} catch (JSONException e) {
String errcode = null;
try {
errcode = json.getString("errcode");
System.out.println("errcode================>获取用户信息失败" + errcode);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
return s;
}
/**
* 获取code请求地址
*
* @param redirect_uri 回调地址 这个回调地址需要在微信公众号后台也进行配置 不然会显示"redirect_uri域名还是与后台配置不一致"
* @param
* @return
*/
public String getCodeUrl(String redirect_uri) {
redirect_uri=URLEncoder.encode(redirect_uri); //使用 urlEncode 对链接进行处理
String codeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize";
codeUrl = codeUrl + "?appid=" + appid + "&redirect_uri=" + redirect_uri
+ "&response_type=code&scope=snsapi_userinfo&state=jetcms#wechat_redirect";
return codeUrl;
}
}
PHP配合微信小程序实现获取手机号码详解
今天刚好做项目的时候用到这块功能,黄啊码就直接上手了,奈何网上的教程各式各样,就是没有个直接可以抄的,啊码最烦说话说一半,今天就直接弄个给大家抄的。
当前通过获取session_key与encryptedData与iv进行解密获取手机号的方法已经不行了,只能通过点击按钮来实现获取微信用户的手机号
1:需要将 button 组件 open-type 的值设置为 getPhoneNumber,当用户点击并同意之后,可以通过 bindgetphonenumber 事件回调获取到动态令牌code,然后把code传到开发者后台,并在开发者后台调用微信后台提供的 phonenumber.getPhoneNumber 接口,消费code来换取用户手机号。每个code有效期为5分钟,且只能消费一次。
注:getPhoneNumber 返回的 code 与 wx.login 返回的 code 作用是不一样的,不能混用。
代码如下:
wxss代码:
<button type="primary"bindgetphonenumber="onGetPhoneNumber" open-type="getPhoneNumber">获取</button>
js代码:
onGetPhoneNumber (e){ if(e.detail.code==null||e.detail.code==""){ wx.showToast({ title: ''请允许获取您的手机号'', ''icon'':''none'', }) return; }else{ wx.request({ data: { code: e.detail.code, time:config.dt, openid: storage.get(''openid'') }, header: {''content-type'': ''application/json''}, url: config.api+''/getWxPhone'', success: function(res) { console.log(res.data.data.phone); } }) } },
2:后端PHP代码【此处我用的是tp5】根据传过来的动态令牌code去获取手机号
/** * @param Request $request * 获取手机号码 */ public function getWxPhone(Request $request){ $params = $request::only([''code'']); $url_get = ''https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=''.config("appid").''&secret=''.config("appsecret"); $tmptoken = json_decode(curlGet($url_get),true); $token = $tmptoken[''access_token'']; $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$token; $data[''code'']=$params[''code'']; $info = Post(json_encode($data),$url); $tmpinfo = json_decode($info,true); $code = $tmpinfo[''errcode'']; $phoneNumber = ""; $phoneNumber = $tmpinfo[''phone_info''][''phoneNumber'']; if($code == ''0''){ self::returnMsg(Error::SUCCESS, ''获取手机号码成功'',[''phone''=>$phoneNumber]); }else{ self::returnMsg(Error::FAILED, ''获取手机号码失败'',['''']); } }
附带函数:
function Post($curlPost, $url, $ssl = false) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost); if (!$ssl) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); } $return_str = curl_exec($curl); curl_close($curl); return $return_str; }
可能出现的错误:errcode“:47001
问题所在:
这里肯定是忘记用json_encode
除了这个问题,某些大聪明娃喜欢把
https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$token
这里的access_token变成data里边的参数,这时候就出现了access_token过期的问题。
一切问题来源于没有好好看官方文档
因为你如果将access_token当做参数,接口就变成了用两次access_token,第一次木有问题,第二次就只能跟你说拜拜了(access_token过期或无效)。
到此这篇关于PHP配合微信小程序实现获取手机号码详解的文章就介绍到这了,更多相关PHP获取手机号码内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
- 微信小程序开发之获取用户手机号码(php接口解密)
- php获取手机端的号码以及ip地址实例代码
- PHP通过API获取手机号码归属地
Python(phone)模块获取手机号归属地、区号、运营商等
一、我使用的是python3,可以自行搜索下载
二、安装phone模块, pip install phone
三、测试代码如下:
from phone import Phone
if __name__ == "__main__":
phoneNum = ''17613394466''
info = Phone().find(phoneNum)
print(info)
try:
phone = info[''phone'']
province = info[''province'']
city = info[''city'']
zip_code = info[''zip_code'']
area_code = info[''area_code'']
phone_type = info[''phone_type'']
except:
print(''none'')
四、批量查询excle中已有的电话号
from phone import Phone
import xlrd
import xlwt
def Get_Excel_data():
file = ''./Tel.xlsx'' #电话号码存储的excle表
re1 = xlrd.open_workbook(file)
outwb = xlwt.Workbook() #创建工作簿
# print(type(outwb))
outws = outwb.add_sheet("new") #在工作簿中新建一个工作表new
# print(type(outws))
# 读取第一个sheet
ws = re1.sheet_by_index(0)
rows = ws.nrows
# print(rows)
outws.write(0, 0, u''电话号'') #给新表的第一行添加对应的标签
outws.write(0, 1, u''省份'')
outws.write(0, 2, u''城市'')
outws.write(0, 3, u''区号'')
outws.write(0, 4, u''运营商'')
for i in range(0, rows):
Telvalue = int(ws.cell_value(i, 0))
# print(Telvalue)
data = Phone().find(Telvalue)
print(data)
outws.write(i + 1, 0, Telvalue) #给新表的个列添加对应的数据
try:
outws.write(i + 1, 1, data[''province''])
outws.write(i + 1, 2, data[''city''])
outws.write(i + 1, 3, data[''area_code''])
outws.write(i + 1, 4, data[''phone_type''])
outwb.save(r''New_Tel.xls'')
except:
print("none")
Get_Excel_data()
参考文章:
https://mp.weixin.qq.com/s/dV2JzXfgjDdCmWRmE0glDA
https://mp.weixin.qq.com/s/an83QZOWXHqll3SGPYTL5g
关于小程序通过用户授权获取手机号之getPhoneNumber和小程序授权获取用户的信息和手机号的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于android – 导入com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder类未找到、JAVA微信公众号网页开发 —— 用户授权获取openid和用户微信信息、PHP配合微信小程序实现获取手机号码详解、Python(phone)模块获取手机号归属地、区号、运营商等的相关信息,请在本站寻找。
本文标签: