phelix/safaricom-sdp

Safaricom SDP平台封装,例如:高级短信(MT和MO)、批量短信等

安装: 40

依赖项: 0

建议者: 0

安全: 0

星标: 10

关注者: 2

分支: 4

语言:TeX

类型:package

v1.0.6 2020-11-20 12:35 UTC

This package is auto-updated.

Last update: 2024-09-20 21:27:25 UTC


README

这是一个用于Safaricom SDP的PHP SDK包装器。Safaricom SDK允许PRSP内容提供商将其系统与Safaricom平台集成。

包含的SDP服务

  • 令牌
    • 获取令牌API:获取令牌
    • 刷新令牌API:获取刷新令牌
  • 订阅API
    • 激活API:用于订阅新用户
    • 取消激活API:用于从订阅中取消用户
  • 高级短信
    • SendSMS API:向高级服务中的用户发送短信
  • 批量短信
    • 批量短信API:向一组用户发送批量短信

要求

  • PHP >= 7.1
  • ext-json
  • ext-openssl
  • ext-mbstring
  • ext-openssl
  • ext-iconv
  • ext-curl
  • guzzlehttp/guzzle: "^7.1"

安装

composer require phelix/safaricom-sdp

如何测试

要测试此包,请将src目录下tests文件夹中的"LoadEnv.php.example"文件复制到"LoadEnv.php",并填写所需的配置值,然后运行以下命令

phpunit test

文档

docs文件夹包含每个类、方法、属性、命名空间等的技术文档。为了使您能够引用以了解一个类的作用或一个函数的作用或每个方法参数的含义,每个文档都有详细描述。

1. 发送高级短信

用于向用户发送高级短信服务;通常是MT消息。

<?php 

    use Phelix\SafaricomSDP\SDP;
    use Phelix\SafaricomSDP\PremiumSMS;
    use Phelix\SafaricomSDP\Exceptions\SDPException;

    try {
        
        // We instantiate the SDP class; passing to it, the api username, api password and the cp id
        $sdp = new SDP($_ENV["SFC_SDP_API_USERNAME"], $_ENV["SFC_SDP_API_PASSWORD"], $_ENV["SFC_SDP_CP_ID"]);
    
        // By default, SDP will use the sandbox apis (test bed), call useLive() method to use production APIs
        $sdp->useLive()->init();
    
        // We instantiate the premium SMS class and pass to it the SDP class
        $premiumSMS = new PremiumSMS($sdp);
        
        // We send SMS
        $requestId = "1234"; // Generate an id that you can use for tracking/logging purposes
        $offerCode = "23456"; // The service for which the sms is being sent
        $linkId = "233348438989"; // This ID is generated when a user requests for a service in SDP.
        $phoneNumber = "254712345678"; // The phone number of the user to receive the message. Format is 2547...
        $message = "This is a test message";
        
        $response = $premiumSMS->sendSMS($requestId, $offerCode, $linkId, $phoneNumber, $message);
        
        // You can check the response and do logging as necessary. Ensure that the status is correctly logged to
        // help in tracking if the request was successful or failed
        if ($response['success']) {
            // Request sent successfully to SDP. Should not be confused to mean the SMS has been successfully 
            // delivered to the user
            
            // We can now check the status of the sent message
            if (isset($response['data']['responseParam'])) {
                
                if ($response['data']['responseParam']['status'] == 1) {
                    // failed to send SMS
                    print("SMS sending failed with status code" . $response['data']['responseParam']['statusCode']. "Error says: ". $response['data']['responseParam']['description']);
                } else {
                    // SMS sending a success. Confirm with the status code and the description and also log them for tracking purposes
                    print($response['data']['responseParam']['description']);
                }
            } else {
                // something wrong seems to have happened. No response param sent back. Handle this for tracking
                print("Seems the response hasn't been sent. Best to assume it failed to send the sms");
            }
            
        } else {
            // Failed to send the request. Could be network, authentication, authorization errors et al 
            print("Sending request failed with message" . $response['errorMessage']);
        }
        
    
    } catch (SDPException $ex) {
        
        // You can do any error logging operations at this point. Exceptions here would most likely occur 
        // at the point of token generation
        
        print $ex->getMessage();
        
    }

1. 激活订阅

用于订阅新用户到服务

<?php 

    use Phelix\SafaricomSDP\SDP;
    use Phelix\SafaricomSDP\Subscription;
    use Phelix\SafaricomSDP\Exceptions\SDPException;

    try {
        
        // We instantiate the SDP class; passing to it, the api username, api password and the cp id
        $sdp = new SDP($_ENV["SFC_SDP_API_USERNAME"], $_ENV["SFC_SDP_API_PASSWORD"], $_ENV["SFC_SDP_CP_ID"]);
    
        // By default, SDP will use the sandbox apis (test bed), call useLive() method to use production APIs
        $sdp->useLive()->init();
    
        // We instantiate the premium SMS class and pass to it the SDP class
        $subscription = new Subscription($sdp);
        
        // We send SMS
        $requestId = "1234"; // Generate an id that you can use for tracking/logging purposes
        $offerCode = "23456"; // The service for which the sms is being sent
        $phoneNumber = "254712345678"; // The phone number of the user to receive the message. Format is 2547...
        
        $response = $subscription->activateSubscription($requestId, $offerCode, $phoneNumber);
        
        // You can check the response and do logging as necessary. Ensure that the status is correctly logged to
        // help in tracking if the request was successful or failed
        if ($response['success']) {
            // Request sent successfully to SDP. Should not be confused to mean the activation has been successfully done 
            
            // We can now check the status of the sent message
            if (isset($response['data']['responseParam'])) {
                
                if ($response['data']['responseParam']['status'] == 1) {
                    // failed to activate subscription
                    print("Activation failed" . $response['data']['responseParam']['statusCode']. "Error says: ". $response['data']['responseParam']['description']);
                } else {
                    // Activation a success. Confirm with the status code and the description and also log them for tracking purposes
                    // Not advisable to assume that this is a success. Always confirm with status code.
                    print($response['data']['responseParam']['description']);
                }
            } else {
                // something wrong seems to have happened. No response param sent back. Handle this for tracking
                print("Seems the response hasn't been sent. Best to assume it failed to activate the user");
            }
            
        } else {
            // Failed to send the request. Could be network, authentication, authorization errors et al 
            print("Failed to send the request" . $response['errorMessage']);
        }
        
    
    } catch (SDPException $ex) {
        
        // You can do any error logging operations at this point. Exceptions here would most likely occur 
        // at the point of token generation
        
        print $ex->getMessage();
        
    }

3. 取消订阅

用于从服务中取消用户订阅

<?php 

    use Phelix\SafaricomSDP\SDP;
    use Phelix\SafaricomSDP\Subscription;
    use Phelix\SafaricomSDP\Exceptions\SDPException;

    try {
        
        // We instantiate the SDP class; passing to it, the api username, api password and the cp id
        $sdp = new SDP($_ENV["SFC_SDP_API_USERNAME"], $_ENV["SFC_SDP_API_PASSWORD"], $_ENV["SFC_SDP_CP_ID"]);
    
        // By default, SDP will use the sandbox apis (test bed), call useLive() method to use production APIs
        $sdp->useLive()->init();
    
        // We instantiate the premium SMS class and pass to it the SDP class
        $subscription = new Subscription($sdp);
        
        // We send SMS
        $requestId = "1234"; // Generate an id that you can use for tracking/logging purposes
        $offerCode = "23456"; // The service for which the sms is being sent
        $phoneNumber = "254712345678"; // The phone number of the user to receive the message. Format is 2547...
        
        $response = $subscription->deactivateSubscription($requestId, $offerCode, $phoneNumber);
        
        // You can check the response and do logging as necessary. Ensure that the status is correctly logged to
        // help in tracking if the request was successful or failed
        if ($response['success']) {
            // Request sent successfully to SDP. Should not be confused to mean the deactivation has been successfully done 
            
            // We can now check the status of the sent message
            if (isset($response['data']['responseParam'])) {
                
                if ($response['data']['responseParam']['status'] == 1) {
                    // failed to activate subscription
                    print("Activation failed" . $response['data']['responseParam']['statusCode']. "Error says: ". $response['data']['responseParam']['description']);
                } else {
                    // Activation a success. Confirm with the status code and the description and also log them for tracking purposes
                    // Not advisable to assume that this is a success. Always confirm with status code.
                    print($response['data']['responseParam']['description']);
                }
            } else {
                // something wrong seems to have happened. No response param sent back. Handle this for tracking
                print("Seems the response hasn't been sent. Best to assume it failed to deactivate the user");
            }
            
        } else {
            // Failed to send the request. Could be network, authentication, authorization errors et al 
            print("Failed to send the request" . $response['errorMessage']);
        }
        
    
    } catch (SDPException $ex) {
        
        // You can do any error logging operations at this point. Exceptions here would most likely occur 
        // at the point of token generation
        
        print $ex->getMessage();
        
    }

4. 发送批量短信

用于向用户发送批量短信

<?php 

    use Phelix\SafaricomSDP\SDP;
    use Phelix\SafaricomSDP\BulkSMS;
    use Phelix\SafaricomSDP\Exceptions\SDPException;

    try {
        
        // We instantiate the SDP class; passing to it, the api username, api password and the cp id
        $sdp = new SDP($_ENV["SFC_SDP_API_USERNAME"], $_ENV["SFC_SDP_API_PASSWORD"], $_ENV["SFC_SDP_CP_ID"]);
    
        // By default, SDP will use the sandbox apis (test bed), call useLive() method to use production APIs
        $sdp->useLive()->init();
    
        // We instantiate the premium SMS class and pass to it the SDP class
        $bulkSMS = new BulkSMS($sdp);
        
        // We send SMS
        $requestId = "1234"; // Generate an id that you can use for tracking/logging purposes
        $username = ""; // Username allocated by the SDP to the partner after successful registration.
        $packageId = ""; // The id of the campaign package as issued upon successful registration
        $originatingAddress = ""; // Originating address assigned to partner after successful registration.
        $recipients = [723345678, 789923456, 79098734];
        $message = "This is a bulk sms";
        $callback = "https://your_call_back_url.com/callback";
        
        $response = $bulkSMS->sendSMS($requestId, $username, $packageId, $originatingAddress, $recipients, $message, $callback);
        
        // You can check the response and do logging as necessary. Ensure that the status is correctly logged to
        // help in tracking if the request was successful or failed
        if ($response['success']) {
            // Request sent successfully to SDP. Should not be confused to mean the bulk has been successfully done 
            
            // We can now check the status of the sent message
            if (isset($response['data'])) {
                
                if ($response['data']['status'] == "SUCCESS") {
                    // Bulk SMS successfully dispatched. This does not mean sent to users; this can only be confirmed from the callback
                    print("Messages successfully dispatched to SDP");
                } else {
                    // Error dispatching bulk SMS to SDP/Safaricom
                    print("Failed to response code ". $response['data']['statusCode']);
                }
            } else {
                // something wrong seems to have happened. No response param sent back. Handle this for tracking
                print("Seems the response hasn't been sent. Best to assume it failed to dispatch the bulk SMS to the users");
            }
            
        } else {
            // Failed to send the request. Could be network, authentication, authorization errors et al 
            print("Failed to send request. Error says " . $response['errorMessage']);
        }
        
    
    } catch (SDPException $ex) {
        
        // You can do any error logging operations at this point. Exceptions here would most likely occur 
        // at the point of token generation
        
        print $ex->getMessage();
        
    }

5. 批量短信回调

用于获取和处理批量短信回调

<?php 

    // put this code in your callback route (controller)
    
    use Phelix\SafaricomSDP\Utils;

    $response = Utils::getCallback();
    
    // get the request id. At this point, you can query your database to get the request so as to be able to update its status
    $requestId = isset($response['requestId']) ? $response['requestId'] : "";
        
    // check status of the callback
    if ($response['success'] == false) {
        // callback received has an error
        
        // update to failed delivery with the error message as the reason
        
        print($response['errorMessage']);
        
    } else {
        
        // correct callback data. 
        $data = $response['data'];
        
        // check the delivery status
 
        $status = $data['responseParam']['status'];
        
        if ($status != 0) {
            // failed to deliver message eg when someone has no airtime or is not subscribed
            print($data['responseParam']['description']);
        } else {
            // message successfully delivered. 
            
            // update request as being a succss
            print("Request $requestId successfully delivered");
        }
    }
    
            

6. SDK通用响应结构

    $response = [
        "success" => true|false,
        "statusCode" => "",
        "statusText" => "",
        "errorCode" => "",
        "errorMessage" => "",
        "data" => [],
        "debugTrace" => [
            'request' => [],
            'response' => []
        ]
    ];
  • success:可以是true | false。表示向SDP提交请求成功,不应与操作成功(例如发送短信)混淆
  • statusCode:来自SDP的HTTP状态码,例如200、400、401、500。适用标准定义
  • statusText:与状态码对应的HTTP状态文本。适用标准定义
  • errorCode:来自SDP的错误码。这取决于特定SDP API的SDP错误码,例如sendSMS、bulkSMS、subscription API可能各自有自己的错误码表示不同的含义
  • errorMessage:SDP描述错误的消息
  • data:在成功的情况下包含来自SDP的响应数据。如果"success"为false,则此值将为null。数据格式取决于使用的特定API
  • debugTrace:此部分包含请求和响应跟踪。如果'SFC_SDP_DEBUG'设置为1,则此值将设置,并有助于调试错误。如果配置值为0,则此字段将为null

7. 示例响应示例

  • 以下描述的所有响应结构均适用于第6节中描述的响应结构中的"data"键。

ii. 获取令牌API

    {
        "msg": "You have been Authenticated to access this protected API System.",
        "token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0dXNlciIsImF1ZCI6IkFDQ0VTUyIsInNjb3BlcyI6IkFETUlOIi wiaXNzIjoiaHR0cDovL3NpeGRlZS5jb20iLCJpYXQiOjE1Njk0OTc1MjksImV4cCI6MTU3NDI5NzUyOX0.- u2Db8OSDhtITMoFqIZYTgs6u4Ib_voynEA6k7ZwiqJqaPQ1_CnUaARxeaoSpC_BC-78_k- rzOr3v2Jdb9_KaA",
        "refreshToken": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0dXNlciIsImF1ZCI6IlJFRlJFU0giLCJzY29wZXMiOiJBRE1J TiIsImlzcyI6Imh0dHA6Ly9zaXhkZWUuY29tIiwianRpIjoiZGIzOTk4OTYtMTU0ZS00ZDFjLTg1NmYtNTUy MDE2MDU3MDVkIiwiaWF0IjoxNTY5NDk3NTI5LCJleHAiOjE1ODAyOTc1Mjl9.uD7fvaMigBI0a2GC00fte qtTx79Elil1CFxRtXz5CTs1qRhJYUVsD0ZjF5Q13J9btY-5ppuzFDqDFkFfUpZAMw"
    }

ii. 刷新令牌API

    {
        "token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0dXNlciIsImF1ZCI6IkFDQ0VTUyIsInNjb3BlcyI6IkFETUlOI iwiaXNzIjoiaHR0cDovL3NpeGRlZS5jb20iLCJpYXQiOjE1Njk0OTc3NTgsImV4cCI6MTU3NDI5Nzc1OH 0.okOMCxGRFd1qt2OLVFFF4eDJ6aPZpLDhkNLA9STVMt9zH7fiMYaNz0S56_tJSXAtxYYq02PoQyG O4WBs716tCg"
    }

iii. 激活订阅API

     {
        "requestId":"17",
        "responseId":"cp2910183038077087336761",
        "responseTimeStamp":"20191104092806",
        "channel":"SMS",
        "operation":"ACTIVATE",
        "requestParam":{
           "data":[
              {
                 "name":"OfferCode",
                 "value":"350032100559"
              },
              {
                 "name":"Msisdn",
                 "value":"795421629"
              },
              {
                 "name":"Language",
                 "value":"1"
              },
              {
                 "name":"CpId",
                 "value":"321"
              }
           ]
        },
        "responseParam":{
           "status":"1",
           "statusCode":"0816",
           "description":"Thank you, your activation of service 5000_Promotional is not processed."
        }
     }

iv. 取消激活API

     {
        "requestId":"17",
        "responseId":"10189519962937756186",
        "responseTimeStamp":"20190924161246",
        "channel":"3",
        "sourceAddress":"224.223.10.27",
        "operation":"DEACTIVATE",
        "requestParam":{
           "data":[
              {
                 "name":"OfferCode",
                 "value":"1001"
              },
              {
                 "name":"Msisdn",
                 "value":"716848648"
              },
              {
                 "value":"10"
              }
           ]
        },
        "responseParam":{
           "status":"0",
           "statusCode":"302",
           "description":"Dear subscriber,You have cancelled your subscription to LOCAL CHANNEL Pack. Thank you for using our service."
        }
     }

v. 发送短信

    // Success. Note responseParam['status']= 0
     {
        "requestId":"17",
        "responseId":"10189519182688287792",
        "responseTimeStamp":"20190924155948",
        "channel":"3",
        "sourceAddress":"224.223.10.27",
        "operation":"SendSMS",
        "requestParam":{
           "data":[
              {
                 "name":"LinkId",
                 "value":"00010310189519161781865526"
              },
              {
                 "name":"Msisdn",
                 "value":"254795421629"
              },
              {
                 "value":"Thank You for Ondemand Subscription SAFRI TEST TUN Subscption test Send sms"
              },
              {
                 "name":"OfferCode",
                 "value":"1003"
              },
              {
                 "value":"10"
              }
           ]
        },
        "responseParam":{
           "status" : 0,
           "statusCode" : 768,
           "description" : "Mesage for xyz sent for processing..."
        }
     }
     
     // Fail. Note responseParam['status']= 1
          {
             "requestId":"17",
             "responseId":"10189519182688287792",
             "responseTimeStamp":"20190924155948",
             "channel":"3",
             "sourceAddress":"224.223.10.27",
             "operation":"SendSMS",
             "requestParam":{
                "data":[
                   {
                      "name":"LinkId",
                      "value":"00010310189519161781865526"
                   },
                   {
                      "name":"Msisdn",
                      "value":"254795421629"
                   },
                   {
                      "value":"Thank You for Ondemand Subscription SAFRI TEST TUN Subscption test Send sms"
                   },
                   {
                      "name":"OfferCode",
                      "value":"1003"
                   },
                   {
                      "value":"10"
                   }
                ]
             },
             "responseParam":{
                "status" : 1,
                "statusCode" : 23,
                "description" : "Subscription does not exists for the subscriber 7299412..."
             }
          }

vi. 批量短信

     {
        "keyword":"Bulk",
        "status":"SUCCESS",
        "statusCode":"SC0000"
     }

vii. 批量短信回调

     {
        "requestId":"",
        "requestTimeStamp":"",
        "channel":"",
        "operation" :"",
        "traceID": "".
        "requestParam": {
            "data" : [
                {
                    "name" : "Msisdn",
                    "value":""
                },
                {
                    "name" : "CpId",
                    "value":""
                },
                {
                    "name" : "CorrelatorId",
                    "value":""
                },
                {
                    "name" : "Description",
                    "value":""
                },
                {
                    "name" : "DeliveryStatus",
                    "value":""
                },
                {
                    "name" : "Type",
                    "value":""
                },
                {
                    "name" : "CampaignId",
                    "value":""
                }
            
            ]
        }
     }

致谢