1024programmer Java Detailed explanation of JavaScript decryption sample code for WeChat applet to obtain mobile phone number

Detailed explanation of JavaScript decryption sample code for WeChat applet to obtain mobile phone number

When we develop WeChat mini programs, a common function is to obtain the user’s mobile phone number, and then log in to the mini program with one click. So how to obtain the mobile phone number? Please read this article carefully to ensure that you can obtain the user’s mobile phone number.

When I first started developing the WeChat applet, I thought about logging in with a mobile phone verification code. Later, I checked the information and learned that text messages sent to users have to be paid for by themselves. Later I thought about it, WeChat can also guarantee the authenticity of the mobile phone number by obtaining the user’s mobile phone number, because since the mobile phone number can be bound to WeChat, it must have been strictly verified, and then the journey of obtaining the mobile phone number began. There are online tutorials There are many, but for some unknown reason, there is always less content. Some have only front-end code and no back-end; some back-end code is PHP, not the Java or Javascript we want. With the idea of ​​open source, I will share with you my method of obtaining a mobile phone number, hoping to help everyone.

First of all, we can take a look at the official documents. Obtaining a mobile phone number is roughly divided into the following four steps:

  • Step 1: Use the wx.login interface to obtain the code (temporary data)
  • Step 2: Use the code in the first step to obtain session_key and openid (confirm the user’s unique data)
  • Step 3: Use the getPhoneNumber interface to obtain iv and encryptedData (obtain encrypted data)
  • Step 4: Decrypt the returned data and obtain the mobile phone number (decrypted data)

Detailed explanation below:

Step one: Use the wx.login interface to obtain the code (temporary data)

The official document says this:

To obtain the mobile phone number bound to a WeChat user, you need to first call the wx.login interface.
Because the user needs to actively trigger the interface to obtain the mobile phone number, this function is not called by the API and needs to be triggered by clicking on the button component.

Note: Currently, this interface is open to non-individual developers and mini programs that have completed certification (excluding overseas entities). It needs to be used with caution. If there are too many reports from users or it is found to be used in unnecessary scenarios, WeChat has the right to permanently revoke the interface permissions of the mini program.

We can extract the following key information:

  • Only non-personal mini programs can obtain user mobile phone numbers.
  • Getting the mobile phone number must be triggered by the button button component, and cannot be written in onLoad() to get it automatically.
  • Use only when necessary.

The first step to obtain the code and run the screenshot are given together with the second step, because these two steps must be written in one method, not two separate methods, and then called in onLoad() , because the applet executes the methods in onLoad() not in the order of the code (speaking from experience)

Step 2: Use the code in the first step to obtain session_key and openid (confirm the user’s unique data)

Sessionkey and openid are the user’s identity certificate. When a user uses a certain applet, the sessionkey is unique. Of course, when a user uses different mini programs, the session key is different.

The official website document says this:

The open-type value of the button component needs to be set to getPhoneNumber. After the user clicks and agrees, the encrypted data returned by the WeChat server can be obtained through the bindgetphonenumber event callback, and then decrypted and obtained by combining session_key and app_id on the third-party server. Phone number.

We need to use the code obtained in the first step to exchange the sessionkey and openid with the server.

The specific code is as follows:

 getLogin: function () {
  var that = this;
  wx.login({
  success: function (res) {
   console.log(res);
   that.setData({
   code: res.code,
   })
   wx.request({
   url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wx846bd21xxxxxxxxx&secret=45135d68ebe49de6fe313xxxxxxxxxxx&js_code=' + that.data.code + '&grant_type=authorization_code',
   method: 'POST',
   header: {
    'content-type': 'application/json'
   },
   success: function (res) {
    console.log(res);
    that.setData({
    sessionkey: res.data.session_key,
    openid: res.data.openid,
    })
   }
   })
  }
  })
 },

We only need to call this method within the onLoad() life cycle function.

This methodfirst calls the wx.login() interface to obtain the code and save it in the page variable code, which is the operation code of the first step.

Thencall the wx.request() interface to request the server in exchange for sessionkey and openid. When copying this code again, you need to replace the appid and secret. These can be Get it on the WeChat public platform.

Under normal circumstances, you can obtain the session key and openid. Of course, if you are a small program for personal authentication, you may get an error. If there are any other errors, please leave a message below the article.

But thisendian to little-endian and vice versa
endian: function (n) {

// If number given, swap endian
if (n.cOnstructor== Number) {
return util.rotl(n, 8) & 0x00FF00FF |
util.rotl(n, 24) & 0xFF00FF00;
}

// Else, assume array and swap all items
for (var i = 0; i 0; n–)
bytes.push(Math.floor(Math.random() * 256));
return bytes;
},

// Convert a byte array to big-endian 32-bit words
bytesToWords: function (bytes) {
for (var words = [], i = 0, b = 0; i >> 5] |= (bytes[i] & 0xFF) <<(24 – b % 32);
return words;
},

// Convert big-endian 32-bit words to a byte array
wordsToBytes: function (words) {
for (var bytes = [], b = 0; b >> 5] >>> (24 – b % 32)) & 0xFF);
return bytes;
},

//Convert a byte array to a hex string
bytesToHex: function (bytes) {
for (var hex = [], i = 0; i >> 4).toString(16));
hex.push((bytes[i] & 0xF).toString(16));
}
return hex.join(“”);
},

//Convert a hex string to a byte array
hexToBytes: function (hex) {
for (var bytes = [], c = 0; c <hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
},

// Convert a byte array to a base-64 string
bytesToBase64: function (bytes) {

// Use browser-native function if it exists
if (typeof btoa == "function") return btoa(Binary.bytesToString(bytes));

for(var base64 = [], i = 0; i <bytes.length; i += 3) {
var triplet = (bytes[i] <<16) | (bytes[i + 1] <<8) | bytes[i + 2];
for (var j = 0; j <4; j++) {
if (i * 8 + j * 6 >> 6 * (3 – j)) & 0x3F));
else base64.push(“=”);
}
}

return base64.join(“”);

},

// Convert a base-64 string to a byte array
base64ToBytes: function (base64) {

// Use browser-native function if it exists
if (typeof atob == “function”) return Binary.stringToBytes(atob(base64));

// Remove non-base-64 characters
base64 = base64.replace(/[^A-Z0-9+\/]/ig, “”);

for (var bytes = [], i = 0, imod4 = 0; i <base64.length; imod4 = ++i % 4) {
if (imod4 == 0) continue;
bytes.push(((base64map.indexOf(base64.charAt(i – 1)) & (Math.pow(2, -2 * imod4 + 8) – 1)) <>> (6 – imod4 * 2)));
}

return bytes;

}

};

// Crypto character encodings
var charenc = Crypto.charenc = {};

// UTF-8 encoding
var UTF8 = charenc.UTF8 = {

//Convert a string to a byte array
stringToBytes: function (str) {
return Binary.stringToBytes(unescape(encodeURIComponent(str)));
},

//Convert a byte array to a string
bytesToString: function (bytes) {
return decodeURIComponent(escape(Binary.bytesToString(bytes)));
}

};

// Binary encoding
var Binary = charenc.Binary = {

//Convert a string to a byte array
stringToBytes: function (str) {
for (var bytes = [], i = 0; i <str.length; i++)
bytes.push(str.charCodeAt(i) & 0xFF);
return bytes;
},

//Convert a byte array to a string
bytesToString: function (bytes) {
for (var str = [], i = 0; i <bytes.length; i++)
str.push(String.fromCharCode(bytes[i]));
return str.join("");
}

};

})();
}

CryptoMath.js

 (function(){
 
 var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto;
 
 // Shortcut
 var util = C.util;
 
 // Convert n to unsigned 32-bit integer
 util.u32 = function (n) {
 return n >>> 0;
 };
 
 // Unsigned 32-bit addition
 util.add = function () {
 var result = this.u32(arguments[0]);
 for (var i = 1; i ) comparison
 util.gt = function (m, n) {
 return this.u32(m) > this.u32(n);
 };
 
 // Unsigned 32-bit less than (<) comparison
 util.lt = function (m, n) {
 return this.u32(m) <this.u32(n);
 };
 
 })();

Summary

This concludes this article about the detailed explanation of the Javascript decryption sample code for obtaining mobile phone numbers through WeChat mini programs. For more related content about Javascript decryption of mobile phone numbers through WeChat mini programs, please search previous articles or continue to browse the related articles below. I hope you will support me more in the future!

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/697305

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

The latest and most comprehensive programming knowledge, all in 1024programmer.com

© 2023 1024programmer - Encyclopedia of Programming Field
Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

首页
微信
电话
搜索