小程序端:
// 登录,写在app.js中,页面一打开便获取
var that = this;
wx.login({
success: res => {
wx.request({
url: ‘baidu.com’,//用code去接口换取openid的路径
data: {
code: res.code
},
header: {},
method: 'POST',
dataType: 'json',
responseType: 'text',
success: function (res) {
console.log(res);
//将openid存储在本地,方便其他地方调用
wx.setStorage({
key: 'openid',
data: res.data.data.openid,
})
},
fail: function (res) {
// console.log('请求失败)
},
complete: function (res) {
//console.log('已执行)
},
})
}
接口:
//根据小程序code获取微信唯一身份标示openid
public function getOpenId()
{
$code = input('code'); //微信客户端登录后获得
$output = $this->openId($code);
if (isset($output['openid']) && !empty($output['openid'])) {
$r['code']='1';
$r['msg'] = '获取openid成功';
$r['data']=$output;
}else{
$r['code']='0';
$r['msg'] = '获取openid失败';
$r['data']=array();
}
return json($r);
}
//私有方法-调用微信api换取openid
private function openId($code){
$appid = config("wxxcx")['APPID'];
$appsecrte = config("wxxcx")['APPSECRET'];
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $appsecrte . '&js_code=' . $code . '&grant_type=authorization_code';
$ch = curl_init(); //初始化
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = json_decode(curl_exec($ch), true);
curl_close($ch);
return $output;
}
只是获取openid,后期会慢慢修补完善,如有不对,欢迎指正,手动笑脸。
补充::
//获取用户微信绑定手机号
public function getMobile(){
$sessionKey=input('session_key');//用code换取
$encryptedData=input('encryptedData');//加密数据(小程序open-type='getPhoneNumber'时所得)
$iv=input('iv');//加密算法的初始向量
$aesKey = base64_decode($sessionKey);
$aesIV = base64_decode($iv);
$aesCipher = base64_decode($encryptedData);
$result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
$result = json_decode($result,true);
if($result){
return $result['phoneNumber'];
}
return '';
}
2021.01.12补充,新发现了一个获取openid与token更便捷的方法,记录一下,方便以后使用:
//获取token
public function getToken(){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->business_appid."&secret=".$this->business_secret;
$data = file_get_contents($url);
$arr = json_decode($data, true);
echo "<pre>";
var_dump($arr);
}