小程序获取用户手机号
思路,书写用户授权登录,登录后获取用户头像及用户昵称,通过wx.getUserProfile获取用户信息,再通过wx.login获取code 用户id和session_key传后台进行添加入库,跳转至获取手机号页面.
login.wxml:
<button type="primary" open-type="getUserInfo" bind:tap="login">授权登录</button>
login:wxjs
// 授权 login(e){ wx.getUserProfile({ desc: 'desc', success:(res)=>{ // 用户昵称 let nickname=res.userInfo.nickName; // 用户头像 let avatarUrl=res.userInfo.avatarUrl; if(res){ wx.login({ success:ret=>{ // 获取调用接口获取登录凭证(code) let code=ret.code; wx.request({ url: 'http://www.day.com/day1/user/getUserInfo', method:'POST', data:{ code:code, nickname:nickname, avatarUrl:avatarUrl }, success:e=>{ console.log(e); // 储存用户id wx.setStorageSync('id', e.data.data.id) wx.setStorageSync('session_key', e.data.data.session_key) if(e){ //跳转至获取手机号页面 wx.switchTab({ url: '/pages/my/my', }) } } }) } }) } } }) }
结合发送的网址,控制器代码:
// 获取用户信息 public function getUserInfo() { $params = \request()->post(); $appid = "wx64832aa6eaea82b0"; // 从微信公众平台获得secret $secret = "95e2acaf355dbcb443f5cd4748a152ed"; // 发送请求换取openid和sessionkey // $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=".$params['code']."&grant_type=authorization_code"; $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code=" . $params['code'] . "&grant_type=authorization_code";; // 暂使用file_get_contents()发送请求,你可以使用CURL扩展的形式实现 $result = json_decode(file_get_contents($url), true); $params['openid'] = $result['openid']; $params['session_key'] = $result['session_key']; //入库 $res = XcxUser::addUser($params); return json(['code' => 200, 'data' => $params, 'message' => 'ok']); }
模型代码:
<?php namespace app\common\model; use think\Model; class XcxUser extends Model { //连接表名 protected $table='xcx_user'; // 经用户添加信息 public static function addUser($params){ return self::create($params,true); } }
以上代码书写完成后,会进入/pages/my/my页面
my.wxml:
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号</button>
my.wxjs:
getPhoneNumber (e) { // console.log(e.detail.iv) // console.log(e.detail.encryptedData) // 取出用户id let uid=wx.getStorageSync('id'); // 取出用户session_key let session_key=wx.getStorageSync('session_key'); //取出用户iv let iv = e.detail.iv; //取出用户encryptedData let encryptedData = e.detail.encryptedData; // 发送请求 wx.request({ url: 'http://www.day.com/day1/user/getPhoneNumber', method:'POST', data:{ iv:iv, encryptedData:encryptedData, uid:uid, session_key:session_key }, success:res=>{ console.log(res); } }) }
结合以上网址,进行控制器代码:
<?php
namespace app\day1\controller;
use app\common\model\XcxUser;
use app\day1\model\SearchModel;
use app\day1\model\UserModel;
use think\Controller;
use think\Db;
use think\Request;
use app\services\phone\WXBizDataCrypt;
class User extends Controller
{
public function getPhoneNumber() { // 接受参数 $encryptedData = input('encryptedData'); $iv = input('iv'); $sessionKey = input('session_key'); $uid = input('uid'); // 从微信公众平台获得$appid $appid = "wx64832aa6eaea82b0"; $pc = new WXBizDataCrypt($appid, $sessionKey); $errCode = $pc->decryptData($encryptedData, $iv, $data); if ($errCode == 0) { return json(['code' => 200, 'data' => $data, 'message' => 'ok']); } else { return json(['code' => 500, 'message' => $errCode]); } }
}
效果图:
接下来封装的代码:
<?php namespace app\services\phone; $appid = 'wx4f4bc4dec97d474b'; $sessionKey = 'tiihtNczf5v6AKRyjwEUhQ=='; $encryptedData="CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM QmRzooG2xrDcvSnxIMXFufNstNGTyaGS 9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+ 3hVbJSRgv+4lGOETKUQz6OYStslQ142d NCuabNPGBzlooOmB231qMM85d2/fV6Ch evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6 /1Xx1COxFvrc2d7UL/lmHInNlxuacJXw u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn /Hz7saL8xz+W//FRAUid1OksQaQx4CMs 8LOddcQhULW4ucetDf96JcR3g0gfRK4P C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB 6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns /8wR2SiRS7MNACwTyrGvt9ts8p12PKFd lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG 20f0a04COwfneQAGGwd5oa+T8yO5hzuy Db/XcxxmK01EpqOyuxINew=="; $iv = 'r7BXXKkLb8qrSNn05n0qiA=='; $pc = new WXBizDataCrypt($appid, $sessionKey); $errCode = $pc->decryptData($encryptedData, $iv, $data ); if ($errCode == 0) { print($data . "\n"); } else { print($errCode . "\n"); }
error code.php
<?php namespace app\services\phone; /** * error code 说明. * <ul> * <li>-41001: encodingAesKey 非法</li> * <li>-41003: aes 解密失败</li> * <li>-41004: 解密后得到的buffer非法</li> * <li>-41005: base64加密失败</li> * <li>-41016: base64解密失败</li> * </ul> */ class ErrorCode { public static $OK = 0; public static $IllegalAesKey = -41001; public static $IllegalIv = -41002; public static $IllegalBuffer = -41003; public static $DecodeBase64Error = -41004; }
WXBizDataCrypt.php
<?php namespace app\services\phone; /** * 对微信小程序用户加密数据的解密示例代码. * * @copyright Copyright (c) 1998-2014 Tencent Inc. */ use app\services\phone\ErrorCode; class WXBizDataCrypt { private $appid; private $sessionKey; /** * 构造函数 * @param $sessionKey string 用户在小程序登录后获取的会话密钥 * @param $appid string 小程序的appid */ public function __construct( $appid, $sessionKey) { $this->sessionKey = $sessionKey; $this->appid = $appid; } /** * 检验数据的真实性,并且获取解密后的明文. * @param $encryptedData string 加密的用户数据 * @param $iv string 与用户数据一同返回的初始向量 * @param $data string 解密后的原文 * * @return int 成功0,失败返回对应的错误码 */ 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); $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV); $dataObj=json_decode( $result ); if( $dataObj == NULL ) { return ErrorCode::$IllegalBuffer; } if( $dataObj->watermark->appid != $this->appid ) { return ErrorCode::$IllegalBuffer; } $data = $result; return ErrorCode::$OK; } }