作者 王智

修改

@@ -90,4 +90,59 @@ class User extends Api @@ -90,4 +90,59 @@ class User extends Api
90 $this->success('成功', $return); 90 $this->success('成功', $return);
91 } 91 }
92 92
  93 +
  94 + /**
  95 + * 用户接口
  96 + * @ApiTitle (Code换token)
  97 + * @ApiSummary (Code换token)
  98 + * @ApiMethod (POST)
  99 + * @ApiRoute (/api/User/UserCode)
  100 + * @ApiParams (name="code", type="integer", required=true, description="Code")
  101 + * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
  102 + * @ApiReturnParams (name="msg", type="string", required=true, sample="返回成功")
  103 + * @ApiReturn ({
  104 + 'code':'1',
  105 + 'msg':'返回成功',
  106 + 'data':{
  107 + 'token' => token,
  108 + })
  109 + */
  110 + public function UserCode()
  111 + {
  112 + $param = $this->request->param();
  113 +// 授权登录
  114 + $ch = curl_init();
  115 + $appid = "wx6a9080f20326f817";
  116 + $secret = "8fe9780e13dd1fa64b886c4f716cd366";
  117 + $code = $param['code'];
  118 + $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
  119 + curl_setopt($ch, CURLOPT_URL, $url);
  120 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  121 + curl_setopt($ch, CURLOPT_HEADER, 0);
  122 + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  123 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  124 + $output = curl_exec($ch);
  125 + if ($output === FALSE) {
  126 + echo "CURL Error:" . curl_error($ch);
  127 + }
  128 + curl_close($ch);
  129 + $curl_result = json_decode($output, true);
  130 + $openid = $curl_result['openid'];
  131 + $is_open = Db::name('user')->where(['openid' => $openid])->find();
  132 + if (empty($is_open)) {
  133 + $this->error('请先注册授权', '', 99991);
  134 + } else {
  135 + $token = $this->request->token();
  136 + $arr = [
  137 + 'token' => $token,
  138 + 'updatetime' => time(),
  139 + ];
  140 + $res = Db::name("user")->where(['openid' => $openid])->update($arr);
  141 + if (!$res) {
  142 + $this->error('Token更新失败', 0);
  143 + die;
  144 + }
  145 + $this->success('成功', $token);
  146 + }
  147 + }
93 } 148 }