search
HomeWeChat AppletMini Program DevelopmentInstructions for creating login process for WeChat mini program development

Anyone who has logged in with WeChat knows that we need an identifier to record the uniqueness of the user's identity. In WeChat, unionId is the unique ID we need to record, so how to get unionId becomes the key. Divide the project into It is divided into two parts: mini program and background PHP code.

Let’s start with our mini program code

Briefly talk about the js code login process of our mini program

login -> Get code ->getUserInfo gets iv and encryptedData -> passes it to your own server for processing -> returns the result to the applet

var API_URL = "自己的服务器地址";
Page({
 onLoad: function () {
 console.log("iv");
 wx.login({//login流程
 success: function (res) {//登录成功
 if (res.code) {
 var code = res.code;
 wx.getUserInfo({//getUserInfo流程
 success: function (res2) {//获取userinfo成功
 console.log(res2);
 var encryptedData = encodeURIComponent(res2.encryptedData);//一定要把加密串转成URI编码
  var iv = res2.iv;
  //请求自己的服务器
  Login(code,encryptedData,iv);
 }
 })
 
 } else {
 console.log('获取用户登录态失败!' + res.errMsg)
 }
 }
});
}
})

code: used by the server to obtain session#KeyRequired parameters.

IV: Initial vector of encryption algorithm, encryptedData: Encrypted string.

Pass code iv encryptedData to our server

function Login(code,encryptedData,iv){ console.log('code='+code+'&encryptedData='+encryptedData+'&iv='+iv);
 //创建一个dialog
  wx.showToast({
  title: '正在登录...',
  icon: 'loading',
  duration: 10000
  });
  //请求服务器
  wx.request({
  url: API_URL,
  data: {
  code:code,
  encryptedData:encryptedData,
  iv:iv
  },
  method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  header: {
  'content-type': 'application/json'
  }, // 设置请求的 header
  success: function (res) {
  // success
  wx.hideToast();
  console.log('服务器返回'+res.data);
 
  },
  fail: function () {
  // fail
  // wx.hideToast();
  },
  complete: function () {
  // complete
  }
  })
 }

If you look at the document, you should know that the unionId we need is in encryptedData, so the server needs this information to transfer unionId Parse it out.

Server processing logic

First download the WeChat decryption demo

The PHP code selected here is the three class files except the demo, Put it into our own project and call it later.

Here is an explanation of the server's processing flow:

Get the seesionKey through WeChat's interface, and then use the sessionKey and iv to decrypt the encryptedData data to obtain the UnionID.

/**
 * 登录
 *
 * @return Response
 */
 public function weixinlogin( $user_id=null )
 {
  global $App_Error_Conf,$Gift_Ids,$Server_Http_Path,$Is_Local,$Test_User,$Good_Vcode,$WeiXin_Xd_Conf;
  $validator_result = input_validator(array('code','iv','encryptedData'));
  if(!empty($validator_result)){
   return response($validator_result);
  }
  $js_code = $_REQUEST['code'];
  $encryptedData = $_REQUEST['encryptedData'];
  $iv = $_REQUEST['iv'];
  $appid = $WeiXin_Xd_Conf['appid'];
  $secret = $WeiXin_Xd_Conf['secret'];
  $grant_type = $WeiXin_Xd_Conf['grant_type'];
  //从微信获取session_key
  $user_info_url = $WeiXin_Xd_Conf['code2session_url'];
  $user_info_url = sprintf("%s?appid=%s&secret=%s&js_code=%s&grant_type=%",$user_info_url,$appid,$secret,$js_code,$grant_type);
  $weixin_user_data = json_decode(get_url($user_info_url));
  $session_key = $weixin_user_data->session_key;
//解密数据
$data = '';
$wxBizDataCrypt = new WXBizDataCrypt($appid, $session_key);
$errCode=$wxBizDataCrypt>decryptData($appid,$session_key,$encryptedData, $iv, $data );

The data we finally got is the encryptedData we decrypted, which will contain unionId.

The above is the detailed content of Instructions for creating login process for WeChat mini program development. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!