微信公众平台开发笔记

公众号里做网页授权登录(OAuth2.0),流程固定三步:引导用户跳转拿 code → 用 code 换 access_token → 用 token 拉用户信息。下面是我当时用 PHP + CodeIgniter 时的笔记,域名、appid 换成你自己的即可。

网页授权流程

1. URL 跳转

用户第一次访问需要登录的页面时,不要直接渲染业务,先重定向到微信授权地址:

链接跳转

https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".urlencode("http://192.168.43.46/auit/index.php?c=app&m=oauth")."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

注意 redirect_uri 要在公众平台配置白名单;scopesnsapi_userinfo 才能拿昵称头像,snsapi_base 只能静默 openid。state 建议随机化防 CSRF,示例里偷懒写了 STATE

2. 用 code 换 access_token

用户同意后,微信会带着 code 回调你的 redirect_uri

file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->secret."&code=".$_GET['code']."&grant_type=authorization_code");

返回 JSON,解析后拿 access_tokenopenidcode 一次性、短期有效,别重复使用。

3. 拉取用户信息

file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".$data->access_token."&openid=".$data->openid."&lang=zh_CN")

得到昵称、头像等字段,就可以写入 session 或数据库了。

流程示例代码

public function oauth(){
      if (isset($_GET['code'])){
          $data=json_decode(file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->secret."&code=".$_GET['code']."&grant_type=authorization_code"));
          $userInfo=json_decode(file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".$data->access_token."&openid=".$data->openid."&lang=zh_CN"));
          $user = array(
              'openid'  => $userInfo->openid,
              'nickname'     => $userInfo->nickname,
              'headimgurl' => $userInfo->headimgurl
          );
          $this->session->set_userdata($user);
          $this->db->replace('user', $user);
          redirect('client');
      }else{
          echo "出现未知错误,如果重复出现该错误,请联系开发者。错误代码:Oauth:10203";
      }
  }

生产环境建议用 curl 并检查 HTTP 状态、错误码;file_get_contents 入门够用。没有 code 时可能是用户拒绝授权或直接访问了回调地址。

php密码操作(PHP 5 >= 5.5.0, PHP 7)

站内用户密码别明文存。PHP 内置 password_hash / password_verify,默认 bcrypt,够用了。

  1. 加密操作:string password_hash ( string $password , int $algo [, array $options ] )

示例:

password_hash("admin", PASSWORD_DEFAULT);

入库保存返回的长字符串,不要自己加盐重复造轮子。

  1. 判断操作: bool password_verify ( string $password , string $hash )

示例:

password_verify($password, $admin_data->row()->password)

登录时用户输入的明文和库里的 hash 比对即可。OAuth 管的是「谁来了」,密码管的是「站内账号」,两套逻辑别混在一块。

版权声明: 本文首发于 指尖魔法屋-微信公众平台开发笔记https://blog.thinkmoon.cn/post/20-wechat-miniprogram-notes-wechat-php/) 转载或引用必须申明原指尖魔法屋来源及源地址!