request->post('code'); $url = self::CODE_URL . '?appid=' . $wxappSettings['app_id'] . '&secret=' . $wxappSettings['app_secret'] . '&js_code=' . $code . '&grant_type=authorization_code'; $header = ['content-type: application/json']; $result = Http::http_post_json($url, '', $header); if (!empty($result['errcode'])) { $this->error($result['errmsg']); } //获取token $user = UserModel::where('open_id', $result['openid'])->find(); if (empty($user)) { $user = UserModel::create([ 'user_pass' => cmf_password('123456'), 'open_id' => $result['openid'], 'union_id' => $result['unionid'], 'user_type' => 2, 'create_time' => time(), ]); } if (empty($user['unionid'])) { $user->union_id = $result['unionid']; $user->save(); } //写入token $token = md5(uniqid()) . md5(uniqid()); $currentTime = time(); $expireTime = $currentTime + 24 * 3600 * 180; Db::name("user_token")->insert([ 'token' => $token, 'user_id' => $user['id'], 'expire_time' => $expireTime, 'create_time' => $currentTime, 'device_type' => $this->deviceType, ]); $this->success('OK',['token' => $token, 'expires_time' => $expireTime]); } public function test() { /*$url = 'https://api.weixin.qq.com/cgi-bin/openapi/rid/get?access_token={$token}'; $data = '{"rid":1}'; $header = ['content-type: application/json']; $result = Http::http_post_json($url, $data, $header); halt($result);*/ $token = $this->_getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}"; $data = [ 'touser' => 'oQeNu5TLNQBgPOKBoH4wK8VyAHMQ', 'msgtype' => 'text', 'text' => ['content'=>'Hello World'] ]; $header = ['content-type: application/json']; $result = Http::http_post_json($url, json_encode($data), $header); halt($result); } public function _getAccessToken() { $time = time(); $wx_access_token = cmf_get_option('wx_access_token'); if (empty($wx_access_token) || $wx_access_token['expires_time'] < $time) { $wxappSettings = cmf_get_option('wxapp_settings')['default']; $url = self::TOKEN_URL . '?appid=' . $wxappSettings['app_id'] . '&secret=' . $wxappSettings['app_secret'] .'&grant_type=client_credential'; $header = ['content-type: application/json']; $wx_access_token = Http::http_post_json($url, '', $header); $wx_access_token['expires_time'] = $time + $wx_access_token['expires_in']; cmf_set_option('wx_access_token',$wx_access_token); } return $wx_access_token['access_token']; } }