Browse Source

批量上传小程序

master
李可松 4 years ago
parent
commit
f905979c0b
  1. 4
      app/Admin/Controllers/MiniProgramTemplateController.php
  2. 111
      app/Admin/Extensions/Grid/MiniProgramUpload.php
  3. 3
      app/Http/Controllers/Api/TestController.php
  4. 54
      app/Jobs/BatchUploadMiniProgram.php
  5. 112
      app/Service/UploadMiniProgram.php
  6. 1
      upload.bat

4
app/Admin/Controllers/MiniProgramTemplateController.php

@ -43,8 +43,8 @@ class MiniProgramTemplateController extends AdminController
$grid->column('op')
->if(fn() => true)
->then(function ($column) {
// $column->append((new MiniProgramUpload(null, 2))->setKey($this->template_id))->append(' ');
$column->append((new MiniProgramDelTemp)->setKey($this->template_id))->append(' ');
$column->append((new MiniProgramUpload(null, 2))->setKey($this->template_id))->append(' ');
$column->append((new MiniProgramDelTemp)->setKey($this->template_id));
});
});
}

111
app/Admin/Extensions/Grid/MiniProgramUpload.php

@ -1,14 +1,16 @@
<?php
namespace App\Admin\Extensions\Grid;
use App\Models\AdminSetting;
use App\Common\UserStatus;
use App\Jobs\BatchUploadMiniProgram;
use App\Models\Agent;
use App\Models\MiniProgramTemplate;
use App\Models\MiniProgramUploadLog;
use App\Service\OpenPlatform;
use App\Service\UploadMiniProgram;
use Dcat\Admin\Grid\RowAction;
use EasyWeChat\Factory;
use EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Code\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
@ -25,8 +27,8 @@ class MiniProgramUpload extends RowAction
public function __construct($title = null, $action = 1)
{
parent::__construct($title);
$this->action = $action; //$action:1=为指定代理商上传小程序;2=暂未确定
$this->title = $action == 1 ? '上传小程序' : '为所有代理商上传';
$this->action = $action;
$this->title = $action == 1 ? '上传小程序' : '上传给所有代理商';
}
protected function html()
@ -40,16 +42,13 @@ class MiniProgramUpload extends RowAction
public function handle(Request $request)
{
return $this->action == 1 ? $this->uploadOne() : $this->uploadAll();
return $request->action == 1 ? $this->uploadOne() : $this->uploadAll();
}
//注:uploadOne在代理商列表页使用
private function uploadOne()
{
$template = MiniProgramTemplate::orderBy('template_id', 'desc')->first();
/*if (MiniProgramUploadLog::query()->where(['agent_id' => $this->getKey(), 'template_id' => $template->template_id])->exists()) {
return $this->response()->error("该代理商已经上传过模板ID为 {$template->template_id} 的小程序,无需重复上传");
}*/
$agent = Agent::find($this->getKey());
if (empty($agent->appid)) {
@ -57,85 +56,9 @@ class MiniProgramUpload extends RowAction
}
try {
$openPlatform = new OpenPlatform();
$refreshToken = $openPlatform->refreshToken($agent->appid);
if (!$refreshToken) {
return $this->response()->error('获取refresh_token失败');
}
$miniProgram = $openPlatform->miniProgram($agent->appid, $refreshToken);
/** @var Client $code */
$code = $miniProgram['code'] ?? null;
if (!$code) {
return $this->response()->error('获取code失败');
}
$templateId = $template->template_id;
$extJson = json_encode(['extAppid' => $agent->appid]);
$version = $template->user_version;
$description = $agent->company_name;
//提交上传
$commit = $code->commit($templateId, $extJson, $version, $description);
if (!isset($commit['errcode'], $commit['errmsg']) || $commit['errcode'] != 0 || $commit['errmsg'] != 'ok') {
throw new \Exception(isset($commit['errmsg']) ? $commit['errmsg'] : join(',', $commit));
}
//提交审核,文档:https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/code/submit_audit.html
$res = $code->submitAudit([]);
$audit_err_code = $this->auditErrorCode();
if (isset($res['errcode'], $res['errmsg']) && $res['errcode'] == 0 && $res['errmsg'] == 'ok') {
$filename = "mini_program_qrcode/{$agent->id}-{$agent->appid}-demo.jpg";
//保存上传记录
MiniProgramUploadLog::insert([
'agent_id' => $agent->id,
'appid' => $agent->appid,
'user_version' => $template->user_version,
'template_id' => $templateId,
'qrcode' => $filename,
'audit_id' => $res['auditid'],
'created_at' => now(),
]);
//获取体验二维码并保存,30天内只获取一次
$qrcode_path = Storage::path("mini_program_qrcode/{$agent->id}-{$agent->appid}-demo.jpg");
if (!file_exists($qrcode_path) || time() - filemtime($qrcode_path) < 86400 * 30) {
$qrcode = $code->getQrCode();
Storage::put("public/$filename", $qrcode);
}
//设置域名,如果之前已经设置过了将记录下来,不再设置
$host = env('APP_URL');
$redis_key = 'mini_program_set_host:' . substr(md5($host), 0, 10);
if (!Redis::hget($redis_key, $agent->appid)) {
/** @var \EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Domain\Client $domain */
$domain = $miniProgram['domain'];
$param = [
"action" => "add",
"requestdomain" => [$host],
"wsrequestdomain" => [str_replace('http', 'ws', $host)],
"uploaddomain" => [$host],
"downloaddomain" => [$host],
];
$domain->modify($param); //服务器域名,服务器域名多次设置仅第一次成功,这里不校验返回结果正确性
$res = $domain->setWebviewDomain([$host]); //业务域名
if (!isset($res['errcode'], $res['errmsg']) || $res['errcode'] != 0 || $res['errmsg'] != 'ok') {
throw new \Exception("设置业务域名{$host}失败,原因:" . $res['errmsg'] ?? (is_array($res) ? join(',', $res) : '未知'));
}
Redis::hset($redis_key, $agent->appid, 1);
}
new UploadMiniProgram($agent, $template);
return $this->response()->success("上传成功,并已提交审核")->refresh();
} else if (isset($audit_err_code[$res['errcode']])) {
throw new \Exception($audit_err_code[$res['errcode']]);
} else {
throw new \Exception($res['errmsg'] ?? join(',', $res));
}
} catch (\Exception $e) {
} catch (GuzzleException | \Exception $e) {
return $this->response()->error($e->getMessage());
}
}
@ -143,13 +66,25 @@ class MiniProgramUpload extends RowAction
//注:uploadAll在小程序模板列表页使用
private function uploadAll()
{
return true;
//上传单个时,$this->getKey()是代理商ID,上传多个时,是小程序模板ID
$template_id = $this->getKey();
$ids = Agent::whereNotNull('appid')
->where([
['status', '=', UserStatus::NORMAL],
['appid', '<>', ''],
])->pluck('id');
foreach ($ids as $id) {
BatchUploadMiniProgram::dispatch($template_id, $id);
}
return $this->response()->success('已经为所有已注册过小程序,且状态正常的代理商上传小程序。上传需要一定时间,请耐心等待');
}
public function confirm()
{
$last_template_id = MiniProgramTemplate::max('template_id');
if ($this->action == 1) {
$last_template_id = MiniProgramTemplate::max('template_id');
return ["确定要上传模板ID为{$last_template_id}的小程序吗?", ''];
} else {
return ['上传确认', '确定要将此小程序模板上传给所有已审核的代理商吗?'];

3
app/Http/Controllers/Api/TestController.php

@ -3,6 +3,7 @@
namespace App\Http\Controllers\Api;
use App\Common\ProductStatus;
use App\Jobs\BatchUploadMiniProgram;
use App\Models\AgentProduct;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
@ -17,7 +18,7 @@ class TestController
{
public function index()
{
dd(AgentProduct::where('agent_id', 10)->withTrashed()->count());
BatchUploadMiniProgram::dispatch('aaaa', 'bbbb')->delay(now()->addMinutes());
}
/**

54
app/Jobs/BatchUploadMiniProgram.php

@ -0,0 +1,54 @@
<?php
namespace App\Jobs;
use App\Models\Agent;
use App\Models\MiniProgramTemplate;
use App\Service\UploadMiniProgram;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class BatchUploadMiniProgram implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private int $template_id; //小程序模板ID
private int $agent_id;
/**
* Create a new job instance.
*
* @param int $template_id 小程序模板ID
* @param int $agent_id 代理商ID
*/
public function __construct(int $template_id, int $agent_id)
{
$this->template_id = $template_id;
$this->agent_id = $agent_id;
}
/**
* Execute the job.
*
* @return void
* @throws Exception
*/
public function handle()
{
$agent = Agent::find($this->agent_id);
$template = MiniProgramTemplate::find($this->template_id);
if (!$agent || !$template) return;
try {
new UploadMiniProgram($agent, $template);
} catch (GuzzleException | \Exception $e) {
throw new Exception($e->getMessage());
}
}
}

112
app/Service/UploadMiniProgram.php

@ -0,0 +1,112 @@
<?php
namespace App\Service;
use App\Models\Agent;
use App\Models\MiniProgramTemplate;
use App\Models\MiniProgramUploadLog;
use EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Code\Client;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
/**
* 上传小程序
* Class UploadMiniProgram
* @package App\Service
*/
class UploadMiniProgram
{
/**
* UploadMiniProgram constructor.
* @param Agent $agent
* @param MiniProgramTemplate $template
* @throws GuzzleException
* @throws Exception
*/
public function __construct(Agent $agent, MiniProgramTemplate $template)
{
try {
$openPlatform = new OpenPlatform();
$refreshToken = $openPlatform->refreshToken($agent->appid);
if (!$refreshToken) {
throw new Exception('获取refresh_token失败');
}
$miniProgram = $openPlatform->miniProgram($agent->appid, $refreshToken);
/** @var Client $code */
$code = $miniProgram['code'] ?? null;
if (!$code) {
throw new Exception('获取code失败');
}
$templateId = $template->template_id;
$extJson = json_encode(['extAppid' => $agent->appid]);
$version = $template->user_version;
$description = $agent->company_name;
//提交上传
$commit = $code->commit($templateId, $extJson, $version, $description);
if (!isset($commit['errcode'], $commit['errmsg']) || $commit['errcode'] != 0 || $commit['errmsg'] != 'ok') {
throw new Exception(isset($commit['errmsg']) ? $commit['errmsg'] : join(',', $commit));
}
//提交审核,文档:https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/code/submit_audit.html
$res = $code->submitAudit([]);
$audit_err_code = $this->auditErrorCode();
if (isset($res['errcode'], $res['errmsg']) && $res['errcode'] == 0 && $res['errmsg'] == 'ok') {
$filename = "mini_program_qrcode/{$agent->id}-{$agent->appid}-demo.jpg";
//保存上传记录
MiniProgramUploadLog::insert([
'agent_id' => $agent->id,
'appid' => $agent->appid,
'user_version' => $template->user_version,
'template_id' => $templateId,
'qrcode' => $filename,
'audit_id' => $res['auditid'],
'created_at' => now(),
]);
//获取体验二维码并保存,30天内只获取一次
$qrcode_path = Storage::path("mini_program_qrcode/{$agent->id}-{$agent->appid}-demo.jpg");
if (!file_exists($qrcode_path) || time() - filemtime($qrcode_path) < 86400 * 30) {
$qrcode = $code->getQrCode();
Storage::put("public/$filename", $qrcode);
}
//设置域名,如果之前已经设置过了将记录下来,不再设置
$host = env('APP_URL');
$redis_key = 'mini_program_set_host:' . substr(md5($host), 0, 10);
if (!Redis::hget($redis_key, $agent->appid)) {
/** @var \EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Domain\Client $domain */
$domain = $miniProgram['domain'];
$param = [
"action" => "add",
"requestdomain" => [$host],
"wsrequestdomain" => [str_replace('http', 'ws', $host)],
"uploaddomain" => [$host],
"downloaddomain" => [$host],
];
$domain->modify($param); //服务器域名,服务器域名多次设置仅第一次成功,这里不校验返回结果正确性
$res = $domain->setWebviewDomain([$host]); //业务域名
if (!isset($res['errcode'], $res['errmsg']) || $res['errcode'] != 0 || $res['errmsg'] != 'ok') {
throw new Exception("设置业务域名{$host}失败,原因:" . $res['errmsg'] ?? (is_array($res) ? join(',', $res) : '未知'));
}
Redis::hset($redis_key, $agent->appid, 1);
}
throw new Exception("上传成功,并已提交审核");
} else if (isset($audit_err_code[$res['errcode']])) {
throw new Exception($audit_err_code[$res['errcode']]);
} else {
throw new Exception($res['errmsg'] ?? join(',', $res));
}
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
}

1
upload.bat

@ -0,0 +1 @@
git push
Loading…
Cancel
Save