1、初步踏入php
2、改朋友的代码改到头大
3、希望有朋友们帮忙改下
需要实现的结果:微信小程序登录,后端php得到手机号并存入数据库。
现遇到的问题:php代码中地址也加入了,前端一直提示报错,appid,secret也都加入了
前端:
<button
class="authbtn"
open-type="getPhoneNumber"
type="primary"
bindgetphonenumber="myGetPhone">获取手机号</button>
前端js:
myGetPhone(e) {
//console.log(e.deatil.code)
wx.request({
url: `http://ceshi.cn/index.php?phone_code=${e.detail.code}`,
success: (res) => {
console.log(res)
this.setData({
phone: res.data.phone
})
}
})
后端php:
<?php
/**
*
* 接收前端传参
*
*/
$appid = "";
$secret = '';
$code['openid_code'] = $_REQUEST['openid_code'];
$code['phone_code'] = $_REQUEST['phone_code'];
// 请求手机号和access_token
if (!empty($code['phone_code'])) {
$rs = getPhoneNumber($code['phone_code'], $appid, $secret);
echo json_encode($rs);
exit;
}
// 获取access_token
// return string
function getWxToken($appid, $secret)
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
$token = json_decode(file_get_contents($url, true), true);
$token = $token['access_token'];
return $token;
}
// 获取手机号 和access_token
// return array
function getPhoneNumber($code, $appid, $secret)
{
$token = getWxToken($appid, $secret);
$url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token;
$data = json_encode(["code" => $code]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true); // 发送post请求
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 传入post参数
$res = curl_exec($ch);
curl_close($ch);
$arr = [
'access_token' => $token,
'phone' => json_decode($res,true)['phone_info']
];
return $arr;
}