虽然工程项目市场需求,须要加进facebook发送信息。facebook现阶段非官方文件格式中,全力支持的是js初始化faceboook sdk展开发送信息、注册登记等一连串操作方式,但这儿会吧facebook的APPID和出访公钥放进后端,引致应用领域可靠性难题,因此他们在后端展开那些方式论的初始化,会使可靠性提高。
1、具体来说须要注册登记三个facebook开发人员帐号
有关facebook帐号注册登记,现阶段亚洲地区我暂没找出好的方式,即使帐号注册登记号后,采用佩列赫展开发送信息时,会被facebook非官方检验到ip极度,引致封爵。因此提议采用澳门伺服器(或是任一国外伺服器)展开该操作方式。较为麻烦事。
2、帐号注册登记好,去建立应用领域。
3、应用领域建立好,会给你应用领域的APPID和三个个公钥。读懂这三个小东西,前面会加进。即使页面采用了Google译者,因此很多术语可能会不精确。这儿的流程应用领域域即应用领域搜索引擎,应用领域搜索引擎能就行了写三个,接着实用性到host文件格式中方可。
(host文件格式在 C:\Windows\System32\drivers\etc 这儿)4、接着找出facebook发送信息
如图,将本页面设置为图中式样,接着实用性你写的facebook发送信息获得成功后的反弹门牌号。(这儿的反弹门牌号是你他们工程项目中的门牌号)
到这儿facebook开发人员实用性基本上就顺利完成了。前面就须要初始化facebook api,和撰写他们的销售业务方式论了。
这儿贴上标识符:
Controller层标识符:
@UnAuth
@ApiOperation(value = "查看脸书发送信息用户是否绑定", notes = "查看脸书发送信息用户是否绑定(不须要认证)")
@PostMapping("/finduser")
@ApiResponses({
@ApiResponse(code = 200, message = " -1 未传递参数 -2 已注册登记过多个用户 0 去注册登记 1 去登陆 -3 系统错误", response = Integer.class)
})
public FacebookResult findUser(@RequestBody AuthRequest authRequest) {
log.debug("authRequest:{}", authRequest);
if (StringUtils.isEmpty(authRequest)) {
log.debug("authRequest is null ....");
return new FacebookResult(-1, new Customer(), new FacebookResponse());
}
try {
FacebookResponse facebookResponse = JSONObject.toJavaObject(getUserInfo(authRequest.getAccessToken()), FacebookResponse.class);
FacebookResult facebookResult = faceBookLoginService.checkUserBinding(facebookResponse, authRequest.getUserID());
if (facebookResult.getFlag() == 1) {
LoginParams loginParams = new LoginParams();
loginParams.setUsername(facebookResult.getCustomer().getUserName());
//反弹
loginParams.setConsumer(customer -> MobileLoginUtils.getInstance().putCustomerIdToSession(facebookResult.getCustomer().getId()));
loginService.loginFb(loginParams);
}
return facebookResult;
} catch (Exception e) {
e.printStackTrace();
return new FacebookResult(-3, new Customer(), new FacebookResponse());
}
}
@UnAuth
@ApiOperation(value = "脸书用户注册登记", notes = "脸书用户注册登记(不须要认证)")
@PostMapping("/register")
@ApiResponses({
@ApiResponse(code = 200, message = "-1 手机验证码错误 -2 手机号或验证码为空 -3 手机号存在 -4 邮箱格式错误 -5 二次密码不对 -6 昵称为空 -7 用户已有绑定账户 0 失败 获得成功>0", response = Integer.class)
})
public int registerFb(HttpServletRequest request, @RequestBody RegisterData registerData) {
int res = 0;
try {
res = checkRegister(registerServiceApi.registerCustomer(
registerData.getMobile(), registerData.getPassword(), registerData.getRepassword(), registerData.getCode(),
(String) (request.getSession().getAttribute(String.format("%s_%s", CommonConstant.MOBILE_REGISTER_CODE_KEY, registerData.getMobile()))),
registerData.getEmail(), registerData.getNickname(), registerData.getUserId()), request, registerData.getMobile());
} catch (Exception e) {
e.printStackTrace();
return res;
}
return res;
}
/**
* 获得成功请除session中的手机验证码
*
* @param res 返回码
* @param mobile 手机号码
*/
private int checkRegister(int res, HttpServletRequest request, String mobile) {
if (res > 0) {
request.getSession().removeAttribute(String.format("%s_%s", CommonConstant.MOBILE_REGISTER_CODE_KEY, mobile));
}
return res;
}
public static JSONObject getUserInfo(String accessToken) {
HashMap<String, String> params = new HashMap<String, String>();
String fields = "id,name,email";
params.put("access_token", accessToken);
params.put("fields", fields);
String responseResult = null;
JSONObject userInfo = null;
try {
responseResult = HttpClientUtil.doGet("https://graph.facebook.com/me", params);
} catch (Exception e) {
responseResult = "fail";
e.printStackTrace();
}
if (!StringUtils.isEmpty(responseResult)) {
userInfo = JSONObject.parseObject(responseResult);
}
return userInfo;
}
/**
* 用户注册登记实体
*/
@Data
@ApiModel(description = "用户注册登记实体")
private static class RegisterData {
/**
* 手机号码
*/
@ApiModelProperty(value = "手机号码")
private String mobile;
/**
* 密码
*/
@ApiModelProperty(value = "密码")
private String password;
/**
* 密码
*/
@ApiModelProperty(value = "重复密码")
private String repassword;
/**
* 手机验证码
*/
@ApiModelProperty(value = "手机验证码")
private String code;
/**
* 邮箱
*/
@ApiModelProperty(value = "邮箱")
private String email;
/**
* 昵称
*/
@ApiModelProperty(value = "昵称")
private String nickname;
/**
* 脸书id
*/
@ApiModelProperty(value = "脸书id")
private String userId;
}
Controller层这儿的方式论,主要就是后端初始化facebook发送信息页面,用户展开facebook发送信息,发送信息获得成功后会返回三个个Json:
{
"accessToken": "公钥",
"userID": "facebook用户id",
"expiresIn": "",
"signedRequest": "",
"graphDomain": "",
"data_access_expiration_time":""
}
这儿其实只须要公钥和用户id方可,其他字段根据销售业务市场需求展开改动。
拿到公钥后,后端采用HTTPClient展开facebook api 初始化,根据公钥和id拿到用户的相关信息,facebook相关信息返回如下:{
"id":"",
"name":"",
"email":""
}
这儿能他们设置facebook返回的用户数据。
后端设计表时最好设计三个用户关联表,用于关联他们应用领域的用户信息与facebook用户信息。Service层标识符:
/**
* 查看用户是否绑定 *
* @param userId
* @return
*/
FacebookResult checkUserBinding(FacebookResponse facebookResponse, String userId);
/**
* 增绑定新用户
*
* @param faceBookCustomerLink
* @return
*/
int addFaceBookCustomer(FaceBookCustomerLink faceBookCustomerLink);
/**
* 根据用户帐号查询用户是否有绑定多个账户
*/
int queryCustomerByCustomerId(String customerId);
实现类:
@Override
public FacebookResult checkUserBinding(FacebookResponse facebookResponse, String userId) {
if (StringUtils.isEmpty(userId)) {
logger.error("facebook login false auth is null");
return new FacebookResult(-1, new Customer(), facebookResponse);
}
if (faceBookCustomerLinkMapper.queryByUserId(userId) > 1) {
logger.error("facebook login false because find two user ....");
return new FacebookResult(-2, new Customer(), facebookResponse);
}
FaceBookCustomerLink faceBookCustomerLink = faceBookCustomerLinkMapper.queryCustomerByUserId(userId);
if (!Objects.isNull(faceBookCustomerLink) && !StringUtils.isEmpty(faceBookCustomerLink.getCustomerId())) {
Customer customer = customerService.queryCustomerInfoById(faceBookCustomerLink.getCustomerId());
return new FacebookResult(1, customer, facebookResponse);
}
return new FacebookResult(0, new Customer(), facebookResponse);
}
@Override
public int addFaceBookCustomer(FaceBookCustomerLink faceBookCustomerLink) {
if (Objects.isNull(faceBookCustomerLink)) {
logger.error("facebook login fali");
}
return faceBookCustomerLinkMapper.addFaceBookCustomerLink(faceBookCustomerLink);
}
@Override
public int queryCustomerByCustomerId(String customerId) {
if (StringUtils.isEmpty(customerId)) {
logger.error("facebook login fali");
}
return faceBookCustomerLinkMapper.queryByCustomerId(customerId);
}
HttpClientUtil类:
package com.lecshop.util;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.*;
public class HttpClientUtil {
/**
* 调试工具 */
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
/**
* @Title: doGet
* @Description: get方式
* @author Mundo
*/
public static String doGet(String url, Map<String, String> params) {
// 返回结果 String result = "";
// 建立HttpClient对象
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = null;
try {
// 拼接参数,能用URIBuilder,也能直接拼接在?传值,拼在url前面,如下--httpGet = new
// HttpGet(uri+"?id=123"); URIBuilder uriBuilder = new URIBuilder(url);
if (null != params && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
// 或是用
// 顺便说一下不同(setParameter会覆盖同名参数的值,addParameter则不会) // uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
URI uri = uriBuilder.build();
// 建立get请求
httpGet = new HttpGet(uri);
logger.info("出访路径:" + uri);
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 返回200,请求获得成功
// 结果返回
result = EntityUtils.toString(response.getEntity());
logger.info("请求获得成功!,返回数据:" + result);
} else {
logger.info("请求失败!");
}
} catch (Exception e) {
logger.info("请求失败!");
logger.error(ExceptionUtils.getStackTrace(e));
} finally {
// 释放连接
if (null != httpGet) {
httpGet.releaseConnection();
}
}
return result;
}
/** * @Title: doPost
* @Description: post请求
* @param url
* @param params
* @return
* @author Mundo
*/
public static String doPost(String url, Map<String, String> params) {
String result = "";
// 建立httpclient对象
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
try { // 参数键值对
if (null != params && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair pair = null;
for (String key : params.keySet()) {
pair = new BasicNameValuePair(key, params.get(key));
pairs.add(pair);
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
logger.info("返回数据:>>>" + result);
} else {
logger.info("请求失败!,url:" + url);
}
} catch (Exception e) {
logger.error("请求失败");
logger.error(ExceptionUtils.getStackTrace(e));
e.printStackTrace();
} finally {
if (null != httpPost) {
// 释放连接
httpPost.releaseConnection();
}
}
return result;
}
/**
* @Title: sendJsonStr
* @Description: post发送json字符串
* @param url
* @param params
* @return 返回数据
* @author Mundo
*/
public static String sendJsonStr(String url, String params) {
String result = "";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
if (StringUtils.isNotBlank(params)) {
httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
}
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());
logger.info("返回数据:" + result);
} else {
logger.info("请求失败");
}
} catch (IOException e) {
logger.error("请求极度");
logger.error(ExceptionUtils.getStackTrace(e));
}
return result;
}
}
到这儿facebook的发送信息的功能基本上上就已经顺利完成了,最后,一定要切记,facebook发送信息时一定不要采用佩列赫展开发送信息出访,否者基本上上号是一定会被封掉的。