1、登录微信公众平台

开发—>接口权限—>网页授权—>修改

  

2、网页授权,域名应为微信回调一致的域名。

 

 如果报微信网页授权redirect_uri 参数错误,一般有两种情况,1:网页授权域名与代码所写的回调地址域名不一致,或者网页授权域名多加了 http:// 等协议头等不规范地址。2.appId或appSecret写错了,这点很容易被忽略,我就是这样,公司 有两套,一套测试一套生产,我用生成环境的去调测试环境的,搞了半天才发现。

3、功能-->自定义菜单:设置绑定跳转链接

4、要获得unionId要登录微信开放平台,管理中心-->公众号/小程序-->绑定公众号

    

 

5、代码:

 

/**
* 公众号账号绑定入口
*/
public function bind_wx() {
$wechat_callback= "http://".$_SERVER['HTTP_HOST']."/?m=weixin&c=bind&a=wechat_call_back&type=1";
$this->weixin->chkbind($wechat_callback);
}

/**
* 回调
*/
public function wechat_call_back(){
$thirduser = base::load_mod_class("third_user_model","t_base");

$code = $_GET['code'];
$type = str_replace(',', "&",$_GET['type']);//1入口 2绑定或换绑 3解绑 4原账号登录
$type = empty($type)?1:$type;
$oauth2_info = $this->weixin->oauth2_access_token($code);
if(empty($oauth2_info['openid'])){
$this->bind_wx();
exit();
}
if($type ==2){
$userinfo = $this->weixin->oauth2_get_user_info($oauth2_info['access_token'], $oauth2_info['openid']);
if($userinfo){
$sex = $userinfo['sex']=='女'?2:1; //1:男 2:女
//保存openid并生成网站用户
$data =array(
'union_id' => $userinfo['unionid'],
'third_id' => $userinfo['openid'],
'icon' => $userinfo['headimgurl'],
'nickname' => $userinfo['nickname'],
'sex' => $sex,
'status'=>1,
'user_id' => param::cmssession('user_id'),
'created' => SYS_TIME,
);
$old_third_user = $thirduser->GetInfo("third_id='{$oauth2_info['openid']}'","user_id");
if($old_third_user){
$ret = $thirduser->UpdateInfo($data,"third_id='{$oauth2_info['openid']}'");
}else{
$ret = $thirduser->InsertInfo($data);
}
}
}。。。
$this->tpl->display('wx_bind.html');
}

 

 

//查询是否有绑定账号
public function chkbind($wechat_callback){
$callback = urlencode($wechat_callback);
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appId."&redirect_uri=".$callback."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
header("Location: $url");
exit();
}

//生成OAuth2的Access Token
public function oauth2_access_token($code)
{
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appId."&secret=".$this->appSecret."&code=".$code."&grant_type=authorization_code";
$res = $this->http_request($url);
return json_decode($res, true);
}

//获取用户基本信息(OAuth2 授权的 Access Token 获取 未关注用户,Access Token为临时获取)
public function oauth2_get_user_info($access_token, $openid)
{
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
$res = $this->http_request($url);
return json_decode($res, true);
}


//HTTP请求(支持HTTP/HTTPS,支持GET/POST)
protected function http_request($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}

 

数据库设计: