API学习笔记——手机注册API

流程分析

申请 api_key

云片网 https://www.yunpian.com/

1.身份信息验证
2.签名
3.模板

获取api_key 在env 中配置 YUNPIAN_API_KEY =#############(apikey)

获取短信发送组件

composer require "overtrue/easy-sms"

封装 easy-sms 组件方便使用

· touch config/easysms.php 创建一个配置文件 并添加一下内容

 5.0,

    // 默认发送配置
    'default' => [
        // 网关调用策略,默认:顺序调用
        'strategy' => OvertrueEasySmsStrategiesOrderStrategy::class,

        // 默认可用的发送网关
        'gateways' => [
            'yunpian',
        ],
    ],
    // 可用的网关配置
    'gateways' => [
        'errorlog' => [
            'file' => '/tmp/easy-sms.log',
        ],
        'yunpian' => [
            'api_key' => env('YUNPIAN_API_KEY'),
        ],
    ],
];

· 创建一个 ServiceProvider

    php artisan make:provider EasySmsServiceProvider

· 修改该文件

app->singleton(EasySms::class, function ($app) {
            return new EasySms(config('easysms'));
        });

        $this->app->alias(EasySms::class, 'easysms');
    }
}

· config/app.php 注册服务商

AppProvidersEasySmsServiceProvider::class,

调试短信

php artisan thinker


$sms = app('easysms');
try {
    $sms->send(13212345678, [
        'content'  => '【xxx提醒】您的验证码是1234。如非本人操作,请忽略本短信',
    ]);
} catch (OvertrueEasySmsExceptionsNoGatewayAvailableException $exception) {
    $message = $exception->getException('yunpian')->getMessage();
    dd($message);
}

测试成功后就可以接着实现api了

短信接口api构建

添加用户注册route

$api = app('DingoApiRoutingRouter');

$api->version('v1', [
    'namespace' => 'AppHttpControllersApi'
], function($api) {
    // 短信验证码
    $api->post('verificationCodes', 'VerificationCodesController@store')
        ->name('api.verificationCodes.store');
});

数据库迁移 创建phone字段

php artisan make:migration add_phone_to_users_table --table=users

新建表 和 撤销 https://laravelacademy.org/post/130.html 文档

public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('phone')->nullable()->unique()->after('name');
            $table->string('email')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('phone');
            $table->string('email')->nullable(false)->change();
        });
    }

运行迁移

php artisan make:migrate

如果需要修改字段 则需要加上doctrine/dbal组件

composer require doctrine/dbal

创建api表单请求验证类

php artisan make:request Api/VerificationCodeRequest

修改该类文件

 [
                'required',
                'regex:/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))d{8}$/',
                'unique:users'
            ]
        ];
    }
}

创建控制器

php artisan make:controller Api/VerificationCodesController

可以先随便打印一些东西postman测试route打通

编写短信发送逻辑

phone;

        // 生成4位随机数,左侧补0
        $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);

        try {
            $result = $easySms->send($phone, [
                'content'  =>  "【xxx测试】您的验证码是{$code}。如非本人操作,请忽略本短信"
            ]);
        } catch (OvertrueEasySmsExceptionsNoGatewayAvailableException $exception) {
            $message = $exception->getException('yunpian')->getMessage();
            return $this->response->errorInternal($message ?? '短信发送异常');
        }

        $key = 'verificationCode_'.str_random(15);
        $expiredAt = now()->addMinutes(10);
        // 缓存验证码 10分钟过期。
        Cache::put($key, ['phone' => $phone, 'code' => $code], $expiredAt);

        return $this->response->array([
            'key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
        ])->setStatusCode(201);
    }
}

可能会碰到没有安装相关证书curl: (60) SSL certificate problem: unable to get local issuer certificate 错误

下载cacert .pem 放到php目录 打开php.ini 配置curl.cainfo = cacert绝对路径

打开postman 提交手机号 测试短信

参与评论