ECJIA到家短信插件开发

ECJia移动商城系统(EC+)是一款基于移动互联网的商城应用服务产品,重新定义了移动商城系统操作方式及用户体验 ,让用户轻松将商城开到移动设备中,拥有执行效率高、上手轻松、管理便捷等一系列优点。

只要是商城系统就必不可免的会用到短信,今天就教大家如何开发ECJIA到家系统的短信插件,短信接口使用的是短信宝短信平台的短信接口,小伙伴一定会问为什么使用短信宝作为案例呢?原因很简单,因为短信宝的平台极其稳定,而且短信发送速度相当快捷,验证码和订单通知在3~5秒就能收到,用户体验非常好,所以我们公司一直和短信宝保持着合作关系,小伙伴们也可以去短信宝的官网(http://www.smsbao.com)注册一个账号,还有免费的短信条数送呢。

接下来我就说一下开发步骤:第一步我们要清楚目录格式,插件是放在content/plugins目录下,我们首先在plugins文件夹下面建立一个文件夹,名字叫sms_smsbao,在sms_smsbao文件夹下面创建下列文件,languages文件夹、config.php文件、sms_smsbao.class.php文件、sms_smsbao.php文件、SMSbao.php文件。languages文件夹下面需要创建zh_CN文件夹,在zh_CN文件夹下面创建plugin.lang.php文件。文件创建完成之后可以正式开发了。

第二步:打开config.php文件,我们在这个文件中配置短信参数:

<?php


return array(
    'sms_code'      => 'sms_smsbao',

    'check_balance' => true,

    'forms' => array(
       array('name' => 'app_key',           'type' => 'text',       'value' => ''),
       array('name' => 'app_secret',        'type' => 'text',       'value' => ''),
        array('name' => 'app_sign',        'type' => 'text',       'value' => '')
    ),
);

第三步:打开sms_smsbao.class.php文件,这个文件是加载短信宝短信插件的配置信息的。

<?php

defined('IN_ECJIA') or exit('No permission resources.');

use Ecjia\App\Sms\SmsAbstract;

class sms_smsbao extends SmsAbstract
{

    public function setConfig(array $config)
    {
        parent::setConfig($config);

        $this->setAgentConfig();

        $this->agent = royalcms('sms')->driver('smsbao');
    }

    public function setAgentConfig()
    {
        RC_Config::set('sms::sms.agents.smsbao.credentials', [
            'appKey' => $this->config['app_key'],
            'appSecret' => $this->config['app_secret'],
            'appsign' => $this->config['app_sign']
        ]);
    }


    /**
     * 获取插件代号
     *  
     * @see \Ecjia\System\Plugin\PluginInterface::getCode()
     */
    public function getCode()
    {
        return $this->loadConfig('sms_code');
    }

    /** 
     * 加载配置文件
     * 
     * @see \Ecjia\System\Plugin\PluginInterface::loadConfig()
     */
    public function loadConfig($key = null, $default = null)
    {        
        return $this->loadPluginData(RC_Plugin::plugin_dir_path(__FILE__) . 'config.php', $key, $default);
    }

    /** 
     * 加载语言包
     * 
     * @see \Ecjia\System\Plugin\PluginInterface::loadLanguage()
     */
    public function loadLanguage($key = null, $default = null)
    {
        $locale = RC_Config::get('system.locale');
        return $this->loadPluginData(RC_Plugin::plugin_dir_path(__FILE__) . '/languages/'.$locale.'/plugin.lang.php', $key, $default);
    }

}

// end

第四步:打开sms_smsbao.php文件,这个文件是作为安装卸载及使用插件的文件。

<?php

/*
Plugin Name: 短信宝短信
Plugin URI: http://www.smsbao.com
Description: 使用短信宝短信渠道,发送验证码短信、订单通知等。
Author: ECJIA TEAM
Version: 1.0.0
Author URI: http://www.ecjia.com/
Plugin App: sms
*/
defined('IN_ECJIA') or exit('No permission resources.');
class plugin_sms_smsbao {

    public static function install() {
        $config = include(RC_Plugin::plugin_dir_path(__FILE__) . 'config.php');
        $param = array('file' => __FILE__, 'config' => $config);
        return RC_Api::api('sms', 'plugin_install', $param);
    }


    public static function uninstall() {
        $config = include(RC_Plugin::plugin_dir_path(__FILE__) . 'config.php');
        $param = array('file' => __FILE__, 'config' => $config);
        return RC_Api::api('sms', 'plugin_uninstall', $param);
    }

    public static function royalcms_sms_agent_filter($factories) {
        require_once RC_Plugin::plugin_dir_path(__FILE__) . 'SMSbao.php';

        $factories['smsbao'] = 'SMSbao';
        return $factories;
    }

}

Ecjia_PluginManager::extend('sms_smsbao', function() {
    require_once RC_Plugin::plugin_dir_path(__FILE__) . 'sms_smsbao.class.php';
    return new sms_smsbao();
});

RC_Plugin::register_activation_hook(__FILE__, array('plugin_sms_smsbao', 'install'));
RC_Plugin::register_deactivation_hook(__FILE__, array('plugin_sms_smsbao', 'uninstall'));
RC_Hook::add_filter('royalcms_sms_agent_filter', array( 'plugin_sms_smsbao', 'royalcms_sms_agent_filter' ));

// end

第五步:打开SMSbao.php文件,这个文件是短信发送的接口文件。

<?php

use Royalcms\Component\Support\Arr;
use Royalcms\Component\Sms\Sms;
use Royalcms\Component\Sms\Contracts\SmsAgent;

class SMSbao extends Sms implements SmsAgent
{

    const HOST      = 'http://api.smsbao.com/sms?';


    private $appKey;
    private $appSecret;
    private $appSign;

    private $statusStr = array(
        "0" => "短信发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    );

    public function __construct($config)
    {
        $this->config = $config;
        $this->transformConfig();
    }

    public function transformConfig()
    {
        $credentials = Arr::pull($this->config, 'credentials');
        $this->appKey = Arr::pull($credentials, 'appKey');
        $this->appSecret = Arr::pull($credentials, 'appSecret');
        $this->appSign = Arr::pull($credentials, 'appsign');
    }

    protected function authParams()
    {
        return [
            'u'   => $this->appKey,
            'p'  => $this->appSecret,
            'k' =>  $this->appSign
        ];
    }

    /**
     * 发送信息
     * 
     * @see \Royalcms\Component\Sms\Contracts\SmsAgent::send()
     */
    public function send($mobile)
    {
        $url = self::HOST.'u='.$this->appKey.'&p='.md5($this->appSecret).'&m='.$mobile.'&c=【'.$this->appSign.'】'.$this->content;
       $ret = file_get_contents($url);
       return $ret;

    }

    /**
     * 查询账户余额
     */
    public function balance()
    {
        $url = 'http://api.smsbao.com/query?u='.$this->appKey.'&p='.md5($this->appSecret);


        $ret = file_get_contents($url);
       $rest = explode(",",$ret);
        $res['data']['num'] = $rest['1'];
        return $res;



    }

    /**
     * @param $url
     * @param array $body
     * @return array $result
     * @return int $result[].code 返回0则成功,返回其它则错误
     * @return string $result[].msg 返回消息
     * @return string $result[].raw 接口返回的原生信息
     * @return array $result[].data 数据信息
     */
    public function httpRequest($url, array $body)
    {
        $data = [
            'body' => $body
        ];

        $response = $this->sendWithRetry($url, $data);

        $result = $this->transformerResponse($response);

        return $result;
    }

    /**
     * 转换返回的信息处理
     * @param array $response
     * @return array $result
     * @return int $result[].code 返回0则成功,返回其它则错误
     * @return string $result[].msg 返回消息
     * @return string $result[].raw 接口返回的原生信息
     * @return array $result[].data 数据信息
     */
    public function transformerResponse($response)
    {
        $body = $response['body'];
        $result_arr = RC_Xml::to_array($body);

        $data = array();

        if (isset($result_arr['smsid'])) {
            $data['smsid'] = $result_arr['smsid'][0];
            $data['msgid'] = $result_arr['smsid'][0];
        }

        if (isset($result_arr['num'])) {
            $data['num']   = $result_arr['num'][0];
        }

        $result = [
            'raw' => $body,
            'data' => $data,
            'code' => $result_arr['code'][0],
            'description' => $result_arr['msg'][0],
        ];

        if ($result['code'] != '2') {
            return new ecjia_error('ihuyi_error_'.$result['code'], $result['description'], $result);
        }

        return $result;
    }

}

第六步:找到项目/wendor/royalcms/sms/config/sms.php,在agents中添加

  'smsbao' => [
            'credentials' => [
                'appKey' => env('SMSBAO_APPKEY'),
                'appSecret' => env('SMSBAO_APPSECRET'),
                'appsign' => env('SMSBAO_APPSIGN')
            ],
            'executableFile' => 'SMSbao',
        ],

第七步:在项目/vendor/royalcms/sms/Royalcms/Component/Sms/Agents下新建一个文件,取名为SMSbao.php。

<?php

namespace Royalcms\Component\Sms\Agents;

use Royalcms\Component\Support\Arr;
use Royalcms\Component\Sms\Sms;
use Royalcms\Component\Sms\Contracts\SmsAgent;

class SMSbao extends Sms implements SmsAgent
{

    const HOST      = 'http://api.smsbao.com/sms?';


    private $appKey;
    private $appSecret;
    private $appSign;

    private $statusStr = array(
        "0" => "短信发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    );

    public function __construct($config)
    {
        $this->config = $config;
        $this->transformConfig();
    }

    public function transformConfig()
    {
        $credentials = Arr::pull($this->config, 'credentials');
        $this->appKey = Arr::pull($credentials, 'appKey');
        $this->appSecret = Arr::pull($credentials, 'appSecret');
    }

    protected function authParams()
    {
        return [
            'u'   => $this->appKey,
            'p'  => $this->appSecret,
            'k' =>  $this->appSign
        ];
    }

    /**
     * 发送信息
     * 
     * @see \Royalcms\Component\Sms\Contracts\SmsAgent::send()
     */
    public function send($mobile)
    {
        $url = self::HOST;
        $requestParams = array(
            'content' => $this->content,
            'mobile' => $mobile,
        );

        $requestParams = array_merge($this->authParams(), $requestParams);

        return $this->httpRequest($url, $requestParams);
    }

    /**
     * 查询账户余额
     */
    public function balance()
    {
        $url = 'http://api.smsbao.com/query?u='.$this->appKey.'&p='.md5($this->appSecret);


        $ret = file_get_contents($url);
        $retArr = split("\n", $ret);
        $balanceArr = split(",", $retArr[1]);
        $rest = $retArr[0] == 0 ? $balanceArr[1] : $ret;
        return $rest;



    }

    /**
     * @param $url
     * @param array $body
     * @return array $result
     * @return int $result[].code 返回0则成功,返回其它则错误
     * @return string $result[].msg 返回消息
     * @return string $result[].raw 接口返回的原生信息
     * @return array $result[].data 数据信息
     */
    public function httpRequest($url, array $body)
    {
        $data = [
            'body' => $body
        ];

        $response = $this->sendWithRetry($url, $data);

        $result = $this->transformerResponse($response);

        return $result;
    }

    /**
     * 转换返回的信息处理
     * @param array $response
     * @return array $result
     * @return int $result[].code 返回0则成功,返回其它则错误
     * @return string $result[].msg 返回消息
     * @return string $result[].raw 接口返回的原生信息
     * @return array $result[].data 数据信息
     */
    public function transformerResponse($response)
    {
        $body = $response['body'];
        $result_arr = RC_Xml::to_array($body);

        $data = array();

        if (isset($result_arr['smsid'])) {
            $data['smsid'] = $result_arr['smsid'][0];
            $data['msgid'] = $result_arr['smsid'][0];
        }

        if (isset($result_arr['num'])) {
            $data['num']   = $result_arr['num'][0];
        }

        $result = [
            'raw' => $body,
            'data' => $data,
            'code' => $result_arr['code'][0],
            'description' => $result_arr['msg'][0],
        ];

        if ($result['code'] != '2') {
            return new ecjia_error('ihuyi_error_'.$result['code'], $result['description'], $result);
        }

        return $result;
    }

}

好了,短信宝接口替换全部完成。。如果看了文章不清楚的话,在短信宝官网中也提供了插件下载地址:http://www.smsbao.com/plugin/158.html 小伙伴们可以对着短信宝短信插件,来看我这篇文章,这样会更直观一些。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值