一、極光推送官網(https://www.jpush.cn/)申請一個帳號。html
二、服務中心,開發者服務中,建立一個新的應用,輸入正確的Android的包名android
三、獲取到了一個AppKey 和一個 Master Secret,這兩個參數比較重要,驗證權限使用。ios
四、去官網找到下載C# SDK的包https://docs.jiguang.cn/jpush/resources/git
Github 源碼:https://github.com/jpush/jpush-api-csharp-clientgithub
五、源碼生成DLLjson
六、項目引用DLL,新建類 using Jiguang.JPush.Model;c#
七、代碼封裝HTTP 調用官方API,轉載地址爲pohreb博客:http://www.javashuo.com/article/p-dsjbleec-cb.htmlapi
服務器
-
-
-
-
-
private const string AppKey = "填寫你應用的AppKey";
-
-
-
-
private const string MasterSecret = "填寫你的MasterSecret";
-
-
-
-
private const string RequestUrl = "https://api.jpush.cn/v3/push";
-
-
-
-
-
private const string ReceivedUrl = "https://report.jpush.cn/v3/received";
-
-
-
-
-
-
-
-
-
private static string SendRequest(String method, String url, String auth, String reqParams)
-
-
-
HttpWebRequest myReq =
null;
-
HttpWebResponse response =
null;
-
-
-
myReq = (HttpWebRequest)WebRequest.Create(url);
-
-
myReq.ContentType =
"application/json";
-
if (!String.IsNullOrEmpty(auth))
-
-
myReq.Headers.Add(
"Authorization", "Basic " + auth);
-
-
-
-
byte[] bs = UTF8Encoding.UTF8.GetBytes(reqParams);
-
myReq.ContentLength = bs.Length;
-
using (Stream reqStream = myReq.GetRequestStream())
-
-
reqStream.Write(bs,
0, bs.Length);
-
-
-
-
response = (HttpWebResponse)myReq.GetResponse();
-
HttpStatusCode statusCode = response.StatusCode;
-
if (Equals(response.StatusCode, HttpStatusCode.OK))
-
-
using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
-
-
resultJson = reader.ReadToEnd();
-
-
-
object json = Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson);
-
-
-
-
resultJson =
string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": 10086}}}}", "響應的結果不是正確的json格式");
-
-
-
-
-
-
-
if (ex.Status == WebExceptionStatus.ProtocolError)
-
-
HttpStatusCode errorCode = ((HttpWebResponse)ex.Response).StatusCode;
-
string statusDescription = ((HttpWebResponse)ex.Response).StatusDescription;
-
using (StreamReader sr = new StreamReader(((HttpWebResponse)ex.Response).GetResponseStream(), System.Text.Encoding.UTF8))
-
-
resultJson = sr.ReadToEnd();
-
-
Dictionary<
string, object> dict = JsonToDictionary(resultJson);
-
string errCode = "10086";
-
string errMsg = "發送推送的請求地址不存在或沒法鏈接";
-
if (dict.ContainsKey("errcode"))
-
-
errCode = dict[
"errcode"].ToString();
-
-
if (dict.ContainsKey("errmsg"))
-
-
errMsg = dict[
"errmsg"].ToString();
-
-
resultJson =
string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": {1}}}}}", errMsg, errCode);
-
-
-
-
-
-
resultJson =
string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": 10086}}}}", ex.Message.Replace("\"", " ").Replace("'", " "));
-
-
-
catch (System.Exception ex)
-
-
resultJson =
string.Format("{{\"error\": {{\"message\": \"{0}\", \"code\": 10086}}}}", ex.Message.Replace("\"", " ").Replace("'", " "));
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
private static string GetBase64Auth()
-
-
string str = AppKey + ":" + MasterSecret;
-
byte[] bytes = Encoding.Default.GetBytes(str);
-
return Convert.ToBase64String(bytes);
-
-
-
-
-
-
-
-
public static string SendRequest(String method, String reqParams)
-
-
string auth = GetBase64Auth();
-
return SendRequest(method, RequestUrl, auth, reqParams);
-
-
-
-
-
-
-
public static string SendPostRequest(String reqParams)
-
-
string auth = GetBase64Auth();
-
return SendRequest("POST", RequestUrl, auth, reqParams);
-
-
-
-
-
-
-
public static string SendGetRequest(String reqParams)
-
-
string auth = GetBase64Auth();
-
return SendRequest("GET", RequestUrl, auth, reqParams);
-
-
-
-
-
-
-
-
-
-
-
public static string GetReceivedResult(String msg_ids)
-
-
string url = ReceivedUrl + "?msg_ids=" + msg_ids;
-
String auth = GetBase64Auth();
-
return SendRequest("GET", url, auth, null);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public static Hashtable JsonToHashtable(string jsonString)
-
-
-
-
-
-
-
-
-
Hashtable ht =
new Hashtable();
-
object json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
-
-
Newtonsoft.Json.Linq.JObject jsonObject = json
as Newtonsoft.Json.Linq.JObject;
-
-
-
-
-
foreach (Newtonsoft.Json.Linq.JProperty jProperty in jsonObject.Properties())
-
-
Newtonsoft.Json.Linq.JToken jToken = jProperty.Value;
-
-
-
-
value = jToken.ToString();
-
-
ht.Add(jProperty.Name,
value);
-
-
-
-
-
-
-
-
-
-
-
public static bool IsSuccess(string jsonString, out string errorMessage, out string errorCode)
-
-
Hashtable ht = JsonToHashtable(jsonString);
-
-
-
foreach (string key in ht.Keys)
-
-
-
-
-
string errJson = ht[key].ToString();
-
Hashtable htError = JsonToHashtable(errJson);
-
errorMessage = htError[
"message"].ToString();
-
errorCode = htError[
"code"].ToString();
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public static bool IsSuccess(string jsonString, out string errorMessage, out string errorCode, out string sendno, out string msg_id)
-
-
bool result = IsSuccess(jsonString, out errorMessage, out errorCode);
-
Hashtable ht = JsonToHashtable(jsonString);
-
-
-
-
-
sendno = ht[
"sendno"].ToString();
-
msg_id = ht[
"msg_id"].ToString();
-
-
-
-
if (ht.ContainsKey("msg_id"))
-
-
msg_id = ht[
"msg_id"].ToString();
-
-
-
-
-
-
-
-
-
-
public static Dictionary<string, object> JsonToDictionary(string jsonString)
-
-
Dictionary<
string, object> ht = new Dictionary<string, object>();
-
object json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
-
-
Newtonsoft.Json.Linq.JObject jsonObject = json
as Newtonsoft.Json.Linq.JObject;
-
-
-
-
-
foreach (Newtonsoft.Json.Linq.JProperty jProperty in jsonObject.Properties())
-
-
Newtonsoft.Json.Linq.JToken jToken = jProperty.Value;
-
-
-
-
value = jToken.ToString();
-
-
ht.Add(jProperty.Name,
value);
-
-
-
-
八、其中咱們主要使用registration_id的方式推送,也就是經過APP上的用戶Token推送。app
新增兩個實體類一個存儲APP用戶Token,以及設備平臺(安卓,蘋果),一個存儲推送記錄,其實極光官網也有推送記錄。
由於須要推送多個用戶狀況,新添List存儲registration_id
新建返回對象存儲返回信息
擴展方法使用,根據文檔實現JSON格式並調用基本方法實現推送https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/
-
-
-
-
-
-
-
-
-
-
-
-
public static bool SendPushV2(List<string> RegistrationIDList, string title, string senduser, string toid,int contype,string dataid, string strMsg, bool is_production, out string strLog)
-
-
-
-
var parmARR = new Dictionary<string, object>();
-
parmARR.Add(
"dataid", dataid);
-
var mm = new M_PushRegistration();
-
mm.registration_id = RegistrationIDList;
-
-
PushPayload pushPayload =
new PushPayload()
-
-
Platform =
new List<string> { "android", "ios" },
-
-
Notification =
new Notification
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
var strParms = pushPayload.Exp_ModelToJson();
-
strParms.WriteFile(
"log/push");
-
var result = JPushHelperV3.SendPostRequest(strParms);
-
var retM = result.Exp_JsonToModel<M_PushReturn>(1);
-
-
strLog +=
"result=" + result + "&&retModel=" + retM.Exp_ModelToJson();
-
strLog.WriteFile(
"log/push");
-
-
-
-
string[] teacherArr = toid.Split(',');
-
for (int i = 0; i < teacherArr.Length; i++)
-
-
D_T_PushMsg_Exp pushmsgDal =
new D_T_PushMsg_Exp();
-
M_T_PushMsg pushmsgModel =
new M_T_PushMsg();
-
pushmsgModel.Title = title;
-
pushmsgModel.MsgAuthor = senduser;
-
pushmsgModel.MsgContent = strMsg;
-
pushmsgModel.Flag =
true;
-
pushmsgModel.IsRead =
false;
-
pushmsgModel.IsSend =
true;
-
pushmsgModel.Contype = contype;
-
pushmsgModel.Remark1 = teacherArr[i].Exp_IntTryParse();
-
pushmsgModel.AddTime = DateTime.Now;
-
pushmsgModel.SendTime = DateTime.Now;
-
pushmsgModel.Remark2 =
"";
-
pushmsgModel.Remark3 =
false;
-
pushmsgDal.Admin_Add(pushmsgModel);
-
-
strLog =
"向設備推送消息成功\r\n請求參數=" + strParms + "\r\n";
-
-
-
-
-
strLog =
"推送失敗,錯誤碼:" + retM.error.code + ",錯誤信息:" + retM.error.message;
-
-
-
-
-
-
strLog =
"推送異常:" + ex.Message;
-
-
-
-
調用該方法便可實現推送。
九、調試,注意事項。
需改進:該基本方法,返回的錯誤信息不知什麼緣由並非官方給出的錯誤信息,他判斷的是HTTP Status Code 返回的異常,容易迷惑覺得受權失敗。具體錯誤信息能夠去官網查看。或者使用https://api.jpush.cn/v3/push/validate校驗API
擴展方法中的Exp_、Admin_方法爲本身封裝DLL功能,可根據要求自行編寫,只是記錄思路。
開發者服務中-應用設置-推送設置,IOS須要你填寫受權方式,Android下能夠快速集成掃描下載安裝包。
https://docs.jiguang.cn/jpush/client/Android/android_3m/
安裝應用並運行,點擊 便可看見分配給本機的RegId
測試接口中能夠填寫該RegId,進行測試。須要手機能聯網,部分機型可能收不到推送(努比亞部分機型?)
調用測試後能夠在極光開發者服務-推送-推送歷史中查看API類型的推送。
該RegId須要爲極光分配給該應用下的該用戶設備RegId,因此APP端也須要集成極光推送註冊用戶爲極光推送對象,若是不是原生的開發,看你的須要選擇:https://docs.jiguang.cn/jpush/client/client_plugins/
以上爲接口端集成。
擴展記錄——APICloud客戶端集成極光推送(並點擊推送消息跳轉相應頁面)
一、APICloud開發APP應用中端開發須要添加極光推送模塊
二、APP應用中config.xml,加入配置app_key對應的APPKEY
三、 在應用打開時Index.html頁面中加入註冊RegId。
setToken=function() {
var token = $api.getStorage('user.token');
-
-
var jpush = api.require('ajpush');
-
if ('ios' == api.systemType) {
-
jpush.getRegistrationId(
function(ret) {
-
-
var registrationId = ret.id;
-
$api.setStorage(
'user.token', ret.id);
-
-
-
jpush.init(
function(ret0, err0) {
-
-
-
jpush.getRegistrationId(
function(ret) {
-
-
var registrationId = ret.id;
-
$api.setStorage(
'user.token', ret.id);
-
-
-
-
-
四、登錄時須要將該用戶的(Regid)Token,更新到服務器端用戶對應的推送下,也就是上面集成C#中的M_T_PushToken數據表中,方便推送時在裏面尋找對象。
擴展更新——APICloud客戶端推送,傳遞自定義參數,用來點擊通知跳轉頁面。
一、主要是更改發送的參數配置便可,更新c#集成的SendPushV2方法中的部分代碼,極光推送文檔https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/#notification
PushPayload pushPayload = new PushPayload()
Platform =
new List<string> { "android", "ios" },
Audience = mm,
Notification = new Notification
{
Alert = strMsg,
Android = new Android
{
Alert = strMsg,
Title = title,
Style = 1,
BigText = strMsg,
Extras = parmARR
},
IOS = new IOS
{
Alert = strMsg,
Badge = "+1",
Extras = parmARR
}
},
Options = new Options
{
IsApnsProduction = true
}
};
二、中的Extras數據應爲JSON格式數據,c#中 var parmARR = new Dictionary<string, object>();方法實現
三、檢查接口端推送數據格式是否正確後,能夠登錄極光官網,(極光開發者服務-相應應用推送-發送通知)中模擬推送,選擇須要的通知樣式。選擇大段文本樣式,能夠解決推送內容過多顯示不全狀況。
四、接口端配置完成後,須要在客戶端監聽通知點擊事件。注意點擊後的跳轉地址便可。
var jpush = api.require('ajpush');
api.addEventListener({name:'appintent'}, function(ret,err) {
var data=ret.appParam.ajpush.extra;
openWinExp(data.DWin,data.Win,{"TypeID":data.TypeID});
})
api.addEventListener({name:'noticeclicked'}, function(ret,err) {
var data=ret.appParam.ajpush.extra;
openWinExp(data.DWin,data.Win,{"TypeID":data.TypeID});
})
openWinExp=function(dir,name, parms) {
api.openWin({
name: name,
url: strurl='html/'+ dir + '/' + name + '.html',
bounces: false,
rect: {
x: 0,
y: 0,
w: 'auto',
h: 'auto'
},
delay: 0,
reload: true,
slidBackEnabled: false,
animation: {
type: stnet.setting.animation.type,
duration: 300,
subType: (parms && parms.type) ? 'from_' + parms.type : stnet.setting.animation.subType
},
pageParam: parms
});
}