整合營銷服務(wù)商

          電腦端+手機端+微信端=數(shù)據(jù)同步管理

          免費咨詢熱線:

          php實現(xiàn)登錄短信驗證

          php實現(xiàn)登錄短信驗證

          今天benny要跟大家說這個其實很簡單,就是借用某一個平臺的短信api接口實現(xiàn)短信驗證,說簡單呢,那是因為他的官網(wǎng):http://www.ucpaas.com上有開發(fā)文檔,它可以教會一個小白很快的運用它的接口,并開發(fā)自己的應(yīng)用。這個官網(wǎng)還算人性化的,因為你一注冊,就給了你10塊錢的測試費用來嘗試使用它的api,你要知道一條短信0.055元,10塊錢給你拿來學(xué)習(xí)測試已經(jīng)夠多啦!

          首先,你進(jìn)入官網(wǎng),注冊,然后你就點擊開發(fā)文檔:

          這里有詳細(xì)的介紹你怎么用它的東西,我就不在這里bb啦,看完后我們就直接下載一個php的demo文件來試試!!

          下載后,你就可以看到一個封裝的類Ucpaas.class.php和一個index.php的文件:

          上面的注釋有詳細(xì)的解釋,要用到的參數(shù)啥的,你注冊了賬號后也就自然有了,多看幾遍,有點基礎(chǔ)的人幾分鐘內(nèi)就可以看得懂的啦!

          接著,你就開始閱讀官網(wǎng)下面目錄的內(nèi)容:

          這里有詳細(xì)的介紹,我就只是做一個引導(dǎo)吧,具體的大家去閱讀哦。

          最后,我把這個短信驗證功能在我的項目上實現(xiàn)了,你可以看下我的代碼截圖:

          <?php

          //載入ucpass類

          require('library/Db.class.php');

          require_once('library/Ucpaas.class.php');

          //初始化必填

          $options['accountsid']='******';(這個不能給大家看哦)

          $options['token']='******';(這個不能給大家看哦)

          //初始化 $options必填

          $ucpass=new Ucpaas($options);

          //開發(fā)者賬號信息查詢默認(rèn)為json或xml

          header("Content-Type:text/html;charset=utf-8");

          //短信驗證碼(模板短信),默認(rèn)以65個漢字(同65個英文)為一條(可容納字?jǐn)?shù)受您應(yīng)用名稱占用字符影響),超過長度短信平臺將會自動分割為多條發(fā)送。分割后的多條短信將按照具體占用條數(shù)計費。

          // 驗證碼短信:同一個手機號1分鐘內(nèi)不能超過2條,24小時內(nèi)不能超過8條

          $appId="****";(這個不能給大家看哦)

          $to=$_POST['to'];

          $templateId="244286";

          $string='';

          for ($i=0; $i <4 ; $i++) {

          $string.=rand(0,9);

          }

          $param=$string;

          $db=new DB();

          $sql="select * from mr_user where username=:username";

          $user=$db->row($sql,array('username'=>$to));

          //用戶名存在

          $id=$user['id'];

          if ($user){

          $password=md5($param);

          $update_sql="update mr_user set password='$password' where id='$id'";

          $result_id=$db->query($update_sql);

          if ($result_id){

          $data=$ucpass->templateSMS($appId,$to,$templateId,$param);

          $re='';

          $arr=json_decode($data,true);

          foreach ($arr as $key=> $value) {

          if ($key=='resp') {

          foreach ($value as $key2=> $value2) {

          if ($key2=='respCode') {

          $re=$value2;

          }

          }

          }

          }

          if ($re=='000000') {

          echo 1;//短信已發(fā)送!

          }elseif ($re=='105147') {

          echo 3;//短信發(fā)送太頻繁

          }else{

          echo 2;//號碼輸入有誤

          }

          exit(0);

          }

          else{

          echo 0;//短信發(fā)送出錯!

          }

          }else {

          $data=$ucpass->templateSMS($appId,$to,$templateId,$param);

          $re='';

          $arr=json_decode($data,true);

          foreach ($arr as $key=> $value) {

          if ($key=='resp') {

          foreach ($value as $key2=> $value2) {

          if ($key2=='respCode') {

          $re=$value2;

          }

          }

          }

          }

          if ($re=='000000') {

          $addtime=time();

          $insert_sql="insert into mr_user(username,password,addtime) value(:username,:password,$addtime)";

          $result_id=$db->query($insert_sql,array('username'=>$to,'password'=>md5($param)));

          if ($result_id){

          echo 1;//短信已發(fā)送!

          }else{

          echo 0;//短信發(fā)送出錯!

          }

          }elseif($re='105147'){

          echo 3;//短信發(fā)送太頻繁

          }else{

          echo 2;//號碼輸入有誤

          }

          }

          圖|來源截圖

          不當(dāng)你的世界 只作你的肩膀

          Benny

          技術(shù)帖

          這樣的一個樣式很簡單, 整體思路是首先在布局中要有一個真實的輸入框, 通過透明度隱藏掉。然后覆蓋層上開始寫自定義樣式, 通過動畫布局模擬出你想要的輸入框樣式。


          下圖為美團App等短信驗證碼布局



          接下來使用 vue3 + typescript 實現(xiàn)該功能


          <!-- 模版布局 -->
          <template>
            <div class="input-diy">
              <p>美團App驗證碼輸入框DEMO</p>
              <div class="input-wrap">
                <input 
                  maxlength="4" 
                  type="number" 
                  v-model="currentPwd"
                  />
                <span 
                  v-for="(val, index) in pwdList" 
                  :key="index"
                  :class="customClass(index)">
                  {{ pwdArr[index] }}
                  </span>
              </div>
            </div>
          </template>

          // 邏輯代碼
          <script lang="ts">
          import { 
            ref, 
            watch,
            reactive, 
            defineComponent, 
          } from 'vue';
          export default defineComponent({
            setup() { 
                let currentPwd=ref<string>(''), // 輸入的驗證碼值
                pwdArr=reactive<string[]>([]), // 輸入框內(nèi)的值
                pwdLength=ref<number | null>(0),  // 已經(jīng)輸入的驗證碼長度,默認(rèn)為0,顯示光標(biāo)
                pwdList=reactive<boolean[]>([false, false, false, false]); // 初始化驗證碼數(shù)據(jù)
              
              watch(()=>{
                return currentPwd.value;
              }, (val)=>{
                watchCurrentPwd(val);
              })
          
              /**
               * 監(jiān)聽input驗證碼改變
               */
              const watchCurrentPwd=(newVal: String)=> {
                  let nval=newVal.toString().replace(/\s+/g,"");
                  pwdLength.value=nval.length || 0; 
                  pwdList.forEach((val: boolean, i: number)=> {
                    pwdArr[i]=nval.slice(i, i + 1); // 獲取輸入inputvalue放入驗證碼框
                  });
                  if(nval.length > 4) { // 截取四位數(shù)據(jù)
                    currentPwd.value=nval.slice(0, 4);
                  } else if( nval.length===4 ) {
                    pwdLength.value=null; // 輸完驗證碼 取消光標(biāo)
                  }
              } 
          
              /**
               * 自定義類名
               */
              const customClass=(index: Number)=> {
                return  index===pwdLength.value ? 'active' : '';
              }
              return {
                pwdArr,
                pwdList,
                pwdLength,
                currentPwd,
                customClass
              }
            }
          });
          </script>

          /* CSS 樣式 */
          <style  scope>
            .input-wrap {
              position: relative;
              display: flex;
              justify-content: center;
              margin-top: 25px;
              overflow: hidden;
            }
          
            /* 真實輸入框 */
            .input-wrap input {
              opacity: 0;
              color: transparent;
              position: absolute;
              top: 0;
              left: -50%;
              /*bottom: 0;*/
              width: 750px;
              height: 150%;
              z-index: 2;
              text-align: left;
            }
          
            /* 模擬驗證碼輸入框 */
            .input-wrap span {
              width: 60px;
              height: 60px;
              border-bottom: 2px solid #BDC2CC;
              margin-right: 25px;
              position: relative;
              top: 0;
              left: 0;
              text-align: center;
              line-height: 60px;
              font-size: 28px;
              color: #303747;
          
            }
          
            .input-wrap span:last-child {
              margin-right: 0;
            }
          
            /*模擬光標(biāo)底部*/
            .input-wrap .active {
              border-bottom: 2px solid #22242A;
            }
          
            /*模擬光標(biāo)閃爍*/
            .input-wrap .active:after {
              content: '';
              position: absolute;
              bottom: -2px;
              left: 30px;
              display: block;
              width: 2px;
              height: 30px;
              background-color: #22242A;
              transform: translate(-50%, -50%);
              animation: focus 1s infinite;
            }
          
            .input-wrap-diy{
              position: relative;
            }
          
            /* 光標(biāo)動畫 */
            @keyframes focus {
              0% {
                opacity: 1
              }
              50% {
                opacity: 1
              }
              51% {
                opacity: 0
              }
              99% {
                opacity: 0
              }
            }
          </style>

          你學(xué)廢了么? 如果想了解更多的web小程序開發(fā)知識, 請點贊收藏加關(guān)注啊。手?jǐn)]不易!持續(xù)更新...

          DEMO效果圖

          了密碼加密之外,驗證碼也是安全性的保障之一。開發(fā)B/S的同學(xué),應(yīng)該很清楚,它可以防止不法分子在短時間內(nèi)用機器批量的重復(fù)操作,防止機器人程序暴力登錄或攻擊。

          如今,為了提高破解難度,有12306購票驗證那種,還有眾多平臺拼圖那種,常見的是咱們這次要說的,由隨機數(shù)字和字母組成這種。

          1

          在Django框架中,你可以自己寫一個生成驗證碼的類,也可以別人已經(jīng)寫好并且開源的第3方驗證碼庫:captcha。

          不懂得偷懶的程序猿不是好工程師,在能滿足需求的前期下,考慮先用現(xiàn)成的。要讓django項目支持captcha,請打開【終端】,輸入:pip3 install django-simple-captcha命令。

          2

          安裝完captcha開發(fā)庫后,打開django項目,進(jìn)行配置。目標(biāo)定位到settings.py文件中的INSTALLED_APPS節(jié)點,在其最后添加上captcha。

          還記得上一次,在此添加sales后,咱們做了什么動作么?--沒錯,就是生成數(shù)據(jù)庫表結(jié)構(gòu),這次也不例外,還是執(zhí)行:python3 manage.py makemigrations和python3 manage.py migrate命令。

          有了數(shù)據(jù)表還不夠,還得提供訪問路徑,否則沒辦法獲取驗證碼。打開sales/urls.py文件,改成如下內(nèi)容。

          from django.urls import include, path

          from . import views

          # 進(jìn)行方法和請求名稱綁定

          urlpatterns=[

          path('index/', views.index),

          path('reg/', views.reg),

          path('captcha/', include('captcha.urls')),

          ]

          3

          配置好了以后,接著就是應(yīng)用了。打開views.py文件,導(dǎo)入生成驗證碼需要用到的模塊并調(diào)整返回登錄界面時的代碼,完整代碼貼出來,拿走不謝。

          from django.shortcuts import render

          from sales.models import UserInfo # 導(dǎo)入models文件

          from erpsite.utils.EncryptUtil import MD5Encrypt

          # 驗證碼需要導(dǎo)入的模塊

          from captcha.models import CaptchaStore

          from captcha.helpers import captcha_image_url

          login_result=''

          reg_result=''

          def reg(request):

          global reg_result

          if request.method=='POST':

          account=request.POST.get('account', '')

          password=request.POST.get('password', '')

          #密碼進(jìn)行加密

          password=MD5Encrypt.encrypt(password)

          print('password:', password)

          try:

          # 將數(shù)據(jù)保存到數(shù)據(jù)庫

          UserInfo.objects.create(account=account, password=password)

          reg_result='恭喜你,注冊成功!'

          except Exception as e:

          reg_result='注冊失敗,錯誤信息:'+str(e)

          return render(request, 'sales/reg.html', {'result': reg_result})

          def index(request):

          global login_result

          if request.method=='POST':

          account=request.POST.get('account', '')

          password=request.POST.get('password', '')

          #密碼進(jìn)行加密

          password=MD5Encrypt.encrypt(password)

          user=UserInfo.objects.filter(account=account, password=password)

          if user.exists():

          login_result='恭喜你,登錄成功!'

          else:

          login_result='登錄賬號或密碼不正確!'

          return render(request, 'sales/index.html', {'result': login_result})

          else:

          #驗證碼,第一次請求

          hashkey=CaptchaStore.generate_key()

          image_url=captcha_image_url(hashkey)

          captcha={'hashkey': hashkey, 'image_url': image_url}

          return render(request, 'sales/index.html', {'captcha': captcha})

          生成好驗證碼后,總得顯示的。打開登錄界面index.html,新增驗證碼顯示的內(nèi)容。完整代碼也粘貼在此,拿走不謝。

          <!DOCTYPE html>

          <html lang="zh">

          <head>

          <meta charset="UTF-8">

          <title>登錄登陸</title>

          </head>

          <body>

          <form action="/sales/index/" method="post">

          {% csrf_token %}

          <h2>用戶登錄</h2>

          <h3 style="color:red;">{{ result }}</h3>

          <p>

          <label for="account">賬號: </label>

          <input type="text" id="account" name="account" placeholder="請輸入賬號" />

          </p>

          <p>

          <label for="password">密碼: </label>

          <input type="password" id="password" name="password" placeholder="請輸入密碼"/>

          </p>

          <p>

          <input type="text" id="code" name="code" placeholder="請輸入驗證碼"/>

          <img src="{{captcha.image_url}}" alt="點擊換一張" id="id_captcha">

          </p>

          <p>

          <input type="submit" value="登 錄"/>

          <a href="/sales/reg" style="margin-left: 10px; text-decoration: none">注 冊</a>

          </p>

          </form>

          </body>

          </html>

          4

          好了,好了。終于可以運行看看效果了, Yeah! Yeah!結(jié)果如你所愿,成功顯示出了驗證碼。

          當(dāng)然,在這個顏值的時代,效果可能沒那么好看,但實際上是可以調(diào)整的。有關(guān)驗證碼的格式,可到進(jìn)行設(shè)置,給出部分參數(shù),請自行調(diào)整去吧。

          # 圖片大小

          CAPTCHA_IMAGE_SIZE=(80, 30)

          CAPTCHA_BACKGROUND_COLOR='#ffff00'

          # 圖片中的文字為隨機英文字母

          CAPTCHA_CHALLENGE_FUNCT='captcha.helpers.random_char_challenge'

          # 圖片中的文字為數(shù)字表達(dá)式

          # CAPTCHA_CHALLENGE_FUNCT='captcha.helpers.math_challenge'

          # 字符個數(shù)

          CAPTCHA_LENGTH=4

          # 超時(minutes)

          CAPTCHA_TIMEOUT=1


          主站蜘蛛池模板: 亚无码乱人伦一区二区| 奇米精品一区二区三区在| 亚洲一区二区三区久久| 视频在线观看一区二区| 亚洲熟妇av一区二区三区下载| 欧洲精品免费一区二区三区| 亚洲夜夜欢A∨一区二区三区| 成人精品一区二区三区校园激情| 日本一区二区不卡视频| 亚洲片国产一区一级在线观看| 亚洲AV日韩AV一区二区三曲| 亚洲AV日韩AV天堂一区二区三区| 亚洲福利精品一区二区三区| 麻豆AV天堂一区二区香蕉| 91久久精品无码一区二区毛片 | 日韩精品一区二区三区大桥未久| 国产中的精品一区的| 精品国产一区二区三区色欲| 国产成人无码一区二区三区在线| 精品视频午夜一区二区| 无码一区二区三区在线| 国产精品视频免费一区二区| 日韩一区二区在线播放| 久久er99热精品一区二区| 无码精品人妻一区二区三区人妻斩 | 国产精品自拍一区| 久久中文字幕一区二区| 久久精品国产第一区二区| 一区二区三区AV高清免费波多| 国产激情一区二区三区小说| 色噜噜狠狠一区二区| 精品福利一区二区三区免费视频| 久久精品亚洲一区二区| 国产一区二区三区在线影院| 波多野结衣的AV一区二区三区 | 国产精品揄拍一区二区| 亚洲一区二区三区国产精品无码| 无码精品黑人一区二区三区 | 波多野结衣一区在线| 动漫精品一区二区三区3d| 色视频综合无码一区二区三区 |