小程序想要获取unionid必需要在微信的开放平台进行绑定,而且注册微信开放平台后需要企业认证,认证费用每年300块钱。这个认证费用和微信公众号是不重叠的,也就是在微信公众号那里还得认证一次交300块。 uninoid的获取有两种方法,一个是通过微信开放的接口jscode2session获取, php代码如下:
$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->appsecret}&js_code={$code}&grant_type=authorization_code";
$resp = ihttp_request($url);
$content= @json_decode($resp['content'],true);
里面的appid和appsecret在小程序管理后台能查看到, 得到的content里面就包含了unionid,openid。
第二种是通过解密encryptedData获取unionid,js代码如下:
wx.getSetting({
success: function(res) {
//wx.getUserInfo需要先通过按钮open-type="getUserInfo" 获取到用户授权,得到encryptedData,传到php进行解密
wx.getUserInfo({
success: function(data) {
(网络请求类).get("weixin/login", {
data: data.encryptedData,
iv:data.iv,
sessionKey: session_key(sessionKey通过wx.login获得)
}, function(e) {
//获取openid和unionid
var openid = e.openId;
var unionid = e.unionid;
}
}
后台php解密代码:
public function decryptData($encryptedData, $iv, &$data)
{
if (strlen($this->sessionKey) != 24) {
return ErrorCode::$IllegalAesKey;
}
$aesKey = base64_decode($this->sessionKey);
if (strlen($iv) != 24) {
return ErrorCode::$IllegalIv;
}
$aesIV = base64_decode($iv);
$aesCipher = base64_decode($encryptedData);
$pc = new Prpcrypt($aesKey);
$result = $pc->decrypt($aesCipher, $aesIV);
if ($result[0] != 0) {
return $result[0];
}
$dataObj = json_decode($result[1]);
if ($dataObj == NULL) {
return ErrorCode::$IllegalBuffer;
}
if ($dataObj->watermark->appid != $this->appid) {
return ErrorCode::$IllegalBuffer;
}
$data = $result[1];
return ErrorCode::$OK;
}
Prpcrypt类代码:
class Prpcrypt
{
public $key;
public function Prpcrypt($k)
{
$this->key = $k;
}
public function decrypt($aesCipher, $aesIV)
{
try {
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($module, $this->key, $aesIV);
$decrypted = mdecrypt_generic($module, $aesCipher);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
}
catch (Exception $e) {
return array(ErrorCode::$IllegalBuffer, NULL);
}
try {
$pkc_encoder = new PKCS7Encoder();
$result = $pkc_encoder->decode($decrypted);
}
catch (Exception $e) {
return array(ErrorCode::$IllegalBuffer, NULL);
}
return array(0, $result);
}
}
提示:小程序在公众号的自定义菜单绑定后提示“未发布”表示不能用开发版绑定,需要正式版本发布后才能在公众号上面通过菜单进入。