#清洗用户微信头像
public function actionAvatar()
{
$wechatParams = \Yii::$app->params['wechat'];
$this->wechatParams = $wechatParams[$this->uniacid];
$app = new Application( $this->wechatParams);
$client = new Client();
$oss = ImageStorageService::getInstance(); # 上传OSS 实例化
$key = 0;
foreach (UserWechat::find()->where(['>','id','3599'])->each(10) as $userdata){
if($userdata['openid'] == 'mod') continue; # 去除模拟用户
$key++;
$openid = UserWechat::getOpenid($userdata['unionid'],$this->uniacid); #获取微信openid
if(empty($openid)) continue;
$user = $app->user->get($openid); #获取该用户的openid
if(empty($user['headimgurl'])) continue;
$avatar = $user['headimgurl']; #获取当前用户头像
if(!empty($userdata->avatar)){
if(strstr($userdata->avatar,'image-yp.cdn.haiwaiuni.com')) continue;
}
$basename = $key.'.png';
$save_path = \Yii::getAlias('@upload').'/avatar/' . $basename;
$response = $client->request('GET', $avatar, [
'headers' => [
'User-Agent' => 'Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)',
'Cookie' => 'Hm_lvt_cd8e5937ea4370821f41c707d5643b7f=1541991577; _ga=GA1.3.517707415.1541991577; _gid=GA1.3.1202663854.1541991577; MEIQIA_EXTRA_TRACK_ID=1CrxSfzll6nIoshf1CYSWdkCS5k; bdshare_firstime=1541991792699; MEIQIA_VISIT_ID=1CsHCsNgcZ2eLmTv5IF5XANXfYf; Hm_lpvt_cd8e5937ea4370821f41c707d5643b7f=1542004665; PHPSESSID=e392a14b61e9458ecbd3497cced9e622; _identity=2b178e67cb2eb7fb85559a27711d546f6dc5c4951a90bf2dd5c57c8505f6a0b0a%3A2%3A%7Bi%3A0%3Bs%3A9%3A%22_identity%22%3Bi%3A1%3Bs%3A49%3A%22%5B4988%2C%22uvleuSgB-eFv4ipo2Dg0VlNfzvKvUW2y%22%2C2592000%5D%22%3B%7D',
]
]);
$text = $response->getBody()->getContents();
if(file_put_contents($save_path,$text)) {
#上传阿里云
$relativeDir = "images/" . date("Y") . "/" . date("m") . "/";
$fileName = md5('user_avatar' . time() . rand(0, 999999)) . '.png';
$remotePath = $relativeDir . $fileName;
$result = $oss->uploadSingleFromFile($remotePath, $save_path);
$img = $result['info']['url'];
#裁剪远程图片
$oss->cutSingleFromRemote($img, [
'width' => 300,
'height' => 300,
'alisa' => 'small',
]);
$img = str_replace('https://cn-haiwaiuni-com.oss-cn-beijing.aliyuncs.com','https://image-yp.cdn.haiwaiuni.com',$img);
$userdata->avatar = $img;
if($userdata->save(false)){
echo 'ID是'. $userdata->id .'的用户,他的昵称是' .$userdata->nickname. '它的头像'.$userdata->avatar .'保存成功啦!';
echo "\n";
}else{
echo '哎呀呀,ID是'. $userdata->id .'的用户,他的昵称是' .$userdata->nickname. '它的头像'.$userdata->avatar .'保存失败啦!';
echo "\n";
}
}else{
echo 'ID是'. $userdata->id .'的用户,他的昵称是' .$userdata->nickname. '它的头像'.$userdata->avatar .'写入文件失败';
}
}
}