>  기사  >  웹 프론트엔드  >  사용자의 개인 정보를 얻기 위해 WeChat 애플릿을 개발하는 방법

사용자의 개인 정보를 얻기 위해 WeChat 애플릿을 개발하는 방법

php中世界最好的语言
php中世界最好的语言원래의
2018-03-23 10:13:455982검색

이번에는 사용자의 개인정보를 얻기 위한 WeChat 애플릿 개발 방법을 보여드리겠습니다. 사용자의 개인정보를 얻기 위한 WeChat 애플릿 개발 시 Notes가 무엇인지 살펴보겠습니다.

최근에 위챗 미니 프로그램 사용법을 공부하고 있어요. 연락을 해보니 많은 함정을 발견했습니다.

예를 들어 브라우저에서는 document.getElementById를 통해 페이지의 DOM 개체를 가져올 수 있습니다. 그러나 WeChat 애플릿에서는 DOM 개체를 얻을 수 없습니다. document.getElementById()는 getElementById가 작동하지 않는다는 오류를 직접 보고합니다. 저도 취했습니다. 이를 지원하지 않으면 많은 흥미로운 기능을 구현할 수 없습니다.
본론으로 돌아가서, 사용자 정보 획득에 대한 내 생각을 말씀드리겠습니다.

사용자 정보를 얻는 방법에는 두 가지가 있습니다.
1. 민감한 정보인 openId(닉네임, 아바타Url 등 기본 정보 포함)가 포함되지 않은 json 객체
2. 민감한 정보인 openId 등의 기본 정보가 포함되어 있습니다.

첫 번째 획득 솔루션

1. 먼저 wx.login() 인터페이스를 호출하여 사용자 인증 확인을 허용합니다. 이는 xxxxx 인증 여부를 육안으로 관찰하는 것입니다.
2. 사용자가 성공적으로 인증된 후 wx.getUserInfo() 인터페이스를 호출하여 사용자 정보를 얻습니다.

완전한 코드는 다음과 같습니다

wx.login({
 success:function(){
 wx.getUserInfo({
  success:function(res){
  var simpleUser = res.userInfo;
  console.log(simpleUser.nickName);
  }
 });
 }
});

두 번째 코드는 더 복잡하고 userInfo를 얻기 위해 배경과의 상호 작용이 필요하지만 이 솔루션으로 얻은 데이터는 완전합니다(openId 포함).

1. 승인을 위해 wx.login() 인터페이스를 호출합니다. 성공 함수의 매개변수 에 코드가 포함되어 있습니다. 2.cryptedData 및 iv가 포함된 wx.getUserInfo() 인터페이스 성공 함수를 호출합니다.
3. 위 매개변수를 백그라운드 분석에 전달하여 userInfo를 생성합니다

코드는 다음과 같습니다

js

var request = require("../../utils/request.js");
wx.login({
 success:function(res_login){
  if(res_login.code)
  {
  wx.getUserInfo({
   withCredentials:true,
   success:function(res_user){
   var requestUrl = "/getUserApi/xxx.php";
   var jsonData = {
    code:res_login.code,
    encryptedData:res_user.encryptedData,
    iv:res_user.iv
    };
   request.httpsPostRequest(requestUrl,jsonData,function(res){
   console.log(res.openId);
   });
   }
  })
  }
 }
 })
백엔드 분석

/**
 * 获取粉丝信息
 * 其中的参数就是前端传递过来的
 */
public function wxUserInfo($code,$encryptedData,$iv)
{
 $apiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->wxConfig['appid']}&secret={$this->wxConfig['appsecret']}&js_code={$code}&grant_type=authorization_code";
 $apiData = json_decode(curlHttp($apiUrl,true),true);
 if(!isset($apiData['session_key']))
 {
 echoJson(array(
  "code" => 102,
  "msg" => "curl error"
 ),true);
 }
 $userInfo = getUserInfo($this->wxConfig['appid'],$apiData['session_key'],$encryptedData,$iv);
 if(!$userInfo)
 {
 echoJson(array(
  "code" => 105,
  "msg" => "userInfo not"
 ));
 }
 //$userInfo = json_decode($userInfo,true);
 //载入用户服务
 //$userService = load_service("User");
 //$userService->checkUser($this->projectId,$userInfo);
 echo $userInfo; //微信响应的就是一个json数据
}
wxBizDataCrypt.php가 있는 getUserInfo 함수 WeChat에서 공식적으로 제공하는 자료 패키지입니다

curlHttp 함수는 사용자 정의 함수입니다. 이 함수의 소스 코드는 내 글을 확인하세요. curHttp

//获取粉丝信息
function getUserInfo($appid,$sessionKey,$encryptedData,$iv){
 require_once ROOTPATH . "/extends/wxUser/wxBizDataCrypt.php";
 $data = array();
 $pc = new WXBizDataCrypt($appid, $sessionKey);
 $errCode = $pc->decryptData($encryptedData, $iv, $data );
 if ($errCode == 0) {
 return $data;
 } else {
 return false;
 }
}
직접 작성한 작은 도구 request.js

var app = getApp();
//远程请求
var httpsRequest = {
 //http 请求
 https_request : function(obj){
 wx.request(obj);
 },
 //文件上传
 upload_request : function(dataSource){
 wx.uploadFile(dataSource);
 }
};
module.exports = {
 //执行异步请求get
 httpsRequest:function(obj){
 var jsonUrl = {};
 jsonUrl.url = obj.url;
 if(obj.header)jsonUrl.header=obj.header;
 if(obj.type)
  jsonUrl.method = obj.type;
 else
  jsonUrl.method="GET";
 if(obj.data)jsonUrl.data = obj.data;
 obj.dataType?(jsonUrl.dataType=obj.dataType):(jsonUrl.dataType="json");
 jsonUrl.success = obj.success;
 jsonUrl.data.projectId = app.globalData.projectId;
 httpsRequest.https_request(jsonUrl);
 },
 //get 请求
 httpsGetRequest:function(req_url,req_obj,res_func)
 {
 var jsonUrl = {
  url:app.globalData.host + req_url,
  header:{"Content-Type":"application/json"},
  dataType:"json",
  method:"get",
  success:function(res)
  {
  typeof res_func == "function" && res_func(res.data);
  }
 }
 if(req_obj)
 {
  jsonUrl.data = req_obj;
 }
 jsonUrl.data.projectId = app.globalData.projectId;
  httpRequest.https_request(jsonUrl);
 },
 //post 请求
 httpsPostRequest:function(req_url,req_obj,res_func)
 {
 var jsonUrl = {
  url:app.globalData.host + req_url,
  header:{"Content-Type":"application/x-www-form-urlencoded"},
  dataType:"json",
  method:"post",
  success:function(res)
  {
  typeof res_func == "function" && res_func(res.data);
  }
 }
 if(req_obj)
 {
  jsonUrl.data = req_obj;
 }
 jsonUrl.data.projectId = app.globalData.projectId;
  httpsRequest.https_request(jsonUrl);
 },
 //文件上传
 httpsUpload:function(uid,fileDataSource,res_func)
 {
 dataSource = {
  url:app.globalData.host + req_url,
  header:{
  "Content-Type":"multipart/form-data"
  },
  dataType:"json",
  formData : {
  "uid" : uid
  },
  filePath : fileDataSource,
  name : "fileObj",
  success:function(res){
  typeof res_func == "function" && res_func(res);
  }
 }
 httpsRequest.upload_request(dataSource);
 }
};
이 기사의 사례를 읽으신 후 마스터하셨다고 생각합니다. 방법, 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요!

추천 자료:

360 브라우저 호환 모드에서 불완전한 페이지 표시를 처리하는 방법

CSS3을 사용하여 기울기 및 회전 애니메이션 효과를 구현하기

인라인 블록 요소의 기본 간격 지우기

위 내용은 사용자의 개인 정보를 얻기 위해 WeChat 애플릿을 개발하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.