说是手机充值系统有点装了,其实就是调用了聚合数据的支付接口,其实挺简单的事 但是我发现博客园竟然没有类似文章,我就个出头鸟把我的代码贡献出来吧

首先说准备工作:

去聚合数据申请账号-添加手机支付的认证-认证通过后为账户充值。

上述工作完成后,开始准备开发要用到的必要参数:

appid:在个人中心-我的数据中可找到对应的APPKEY(每个不同的接口都需要使用对应的appkey)

openid:个人中心-用户中心-账户信息(这个是唯一的程序中会使用到)

对应的接口都有比较详细的数据接收已经返回参数的说明,具体开发中会用到,具体的请查看链接:https://www.juhe.cn/docs/api/id/85

接下来要准备开发中的用到几个辅助函数,在对应的API文档中有示例代码,也可以使用下面的:

    /// <summary>
/// Http (GET/POST)
/// </summary>
/// <param name="url">请求URL</param>
/// <param name="parameters">请求参数</param>
/// <param name="method">请求方法</param>
/// <returns>响应内容</returns>
static string sendPost(string url, IDictionary<string, string> parameters, string method)
{
if (method.ToLower() == "post")
{
HttpWebRequest req = null;
HttpWebResponse rsp = null;
System.IO.Stream reqStream = null;
try
{
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = method;
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
req.Timeout = ;
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
reqStream = req.GetRequestStream();
reqStream.Write(postData, , postData.Length);
rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
if (reqStream != null) reqStream.Close();
if (rsp != null) rsp.Close();
}
}
else
{
//创建请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8")); //GET请求
request.Method = "GET";
request.ReadWriteTimeout = ;
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); //返回内容
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
/// <summary>
/// 把响应流转换为文本。
/// </summary>
/// <param name="rsp">响应流对象</param>
/// <param name="encoding">编码方式</param>
/// <returns>响应文本</returns>
static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
System.IO.Stream stream = null;
StreamReader reader = null;
try
{
// 以字符流的方式读取HTTP响应
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
return reader.ReadToEnd();
}
finally
{
// 释放资源
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
}
}
/// <summary>
/// 组装普通文本请求参数。
/// </summary>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
static string BuildQuery(IDictionary<string, string> parameters, string encode)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
if (encode == "gb2312")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
}
else if (encode == "utf8")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
}
else
{
postData.Append(value);
}
hasParam = true;
}
}
return postData.ToString();
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
public static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(, , , , , , );
return Convert.ToInt64(ts.TotalSeconds).ToString();
}

这几个函数具体的功能就不用说了 ,是代码很简单,都是网络链接发送请求和接受请求是时用的,我主要介绍的是点中未提供的一些

示例代码中用到了JsonObject这个类 代码中提供的是CSDN的链接,竟然还要2积分才能下载,坑爹啊 在这里我给大家分享出来吧 http://pan.baidu.com/s/1hsqF51y

在项目中应用DLL加入using Xfrog.Net;命名空间

准备工作结束

接下来就进入正式编码阶段了 ,开始前我准备说一下重点,其实接口的代码并不复杂,我想说了还是思路吧

1.验证当前账户余额是否够本次充值:调用 http://op.juhe.cn/ofpay/mobile/yue 具体参数参看:https://www.juhe.cn/docs/api/id/85

2.检测手机号是否可以充值:调用http://op.juhe.cn/ofpay/mobile/telcheck    具体参数参看:https://www.juhe.cn/docs/api/id/85/aid/213

3.调用手机直冲接口:   http://op.juhe.cn/ofpay/mobile/onlineorder       具体参数参看: https://www.juhe.cn/docs/api/id/85/aid/214

4.调用订单查询接口:http://op.juhe.cn/ofpay/mobile/ordersta                具体参数参看:https://www.juhe.cn/docs/api/id/85/aid/586

5.编写回调处理页面:QQ上搜索聚合数据的客服,给他账号和回调地址后,让他帮助设置,具体的回调地址接受参数查看:http://code.juhe.cn/docs/detail/id/1565

具体代码贴出:

            //1.账户余额查询
string url1 = "http://op.juhe.cn/ofpay/mobile/yue"; var parameters1 = new Dictionary<string, string>(); string timestamp = GetTimeStamp();
parameters1.Add("timestamp", timestamp); //当前时间戳,如:1432788379
parameters1.Add("key", appkey);//你申请的key
string signstr =openid+ appkey+timestamp;
parameters1.Add("sign", CommonManager.String.EncryptMD5SystemDefaultMethod(signstr, false, true)); //校验值,md5(&lt;b&gt;OpenID&lt;/b&gt;+key+timestamp),OpenID在个人中心查询 string result1 = sendPost(url1, parameters1, "get"); JsonObject newObj1 = new JsonObject(result1);
String errorCode1 = newObj1["error_code"].Value; //查询余额是否成功
if (errorCode1 == "")
{ //判断余额是否够本次充值
if (double.Parse(newObj1["result"]["money"].Value) > double.Parse(Integrals)) {
//msg.InnerText="余额充足!"; //5.检测手机号码是否能充值
string url5 = "http://op.juhe.cn/ofpay/mobile/telcheck"; var parameters5 = new Dictionary<string, string>(); parameters5.Add("phoneno", phone); //手机号码
parameters5.Add("cardnum", Integrals); //充值金额,目前可选:5、10、20、30、50、100、300
parameters5.Add("key", appkey);//你申请的key string result5 = sendPost(url5, parameters5, "get"); JsonObject newObj5 = new JsonObject(result5);
String errorCode5 = newObj5["error_code"].Value; if (errorCode5 == "")
{
//可以充值
//7.手机直充接口
string url7 = "http://op.juhe.cn/ofpay/mobile/onlineorder"; var parameters7 = new Dictionary<string, string>();
parameters7.Add("phoneno", phone); //手机号码
parameters7.Add("cardnum", Integrals); //充值金额,目前可选:5、10、20、30、50、100、300
parameters7.Add("orderid", orderstr); //商家订单号,8-32位字母数字组合
parameters7.Add("key", appkey);//你申请的key
string md5str = openid + appkey + phone + Integrals + orderstr;
parameters7.Add("sign", CommonManager.String.EncryptMD5SystemDefaultMethod(md5str, false, true)); //校验值,md5(&lt;b&gt;OpenID&lt;/b&gt;+key+phoneno+cardnum+orderid),OpenID在个人中心查询 string result7 = sendPost(url7, parameters7, "get"); JsonObject newObj7 = new JsonObject(result7);
String errorCode7 = newObj7["error_code"].Value; if (errorCode7 == "")
{
msg.InnerText = "充值订单创建成功,等待商户充值后查看订单状态!"; DbSession.Default.FromSql(
@"UPDATE TOP(1) TPropLog SET Jhorderid=@Jhorderid,PropStatus=@PropStatus WHERE ID = @ID")
.AddInputParameter("@ID", DbType.Int32, id)
.AddInputParameter("@PropStatus", DbType.Int32, )
.AddInputParameter("@Jhorderid", DbType.String, newObj7["result"]["sporder_id"].Value)
.Execute();
status.SelectedValue = "";
}
else
{
msg.InnerText = "充值订单失败!失败原因:" + newObj7["reason"].Value;
} }
else
{
msg.InnerText = "手机号不能充值!原因:" + newObj1["reason"].Value;
} }
else
{
msg.InnerText = "余额不足请充值!当前账户余额为:" + newObj1["result"]["money"].Value;
} }
else
{
msg.InnerText="余额查询失败!"; }

里面有几个点注意一下:

1.需要sign签名的几个接口需要按照格式使用MD5进行一个转换,MD5转换的函数网上一大把相信你的项目中也有了我就不提供了 ,按照他提供的格式组织签名就行了

2.我的订单查询接口是写在另外一个函数里的,因为我的逻辑充值后单独可以查询,可根据情况自行更改。

3.回调页面是POST方式传值,所以接受的时候按照他提供的参数接收就行了,根据返回的订单号跟新本地数据

        //聚合话费充值回调页面,页面的设置需要联系聚合客服更改
protected void Page_Load(object sender, EventArgs e)
{ var sporder_id = CommonManager.Web.Request("sporder_id", "");//聚合订单ID
var orderid = CommonManager.Web.Request("orderid", ""); //鼎鼎订单ID
var sta = CommonManager.Web.Request("sta", ""); //充值状态1:成功 9:失败
if (sta == "")
{
//更新订单状态为充值成功
DbSession.Default.FromSql(
@"UPDATE TOP(1) TPropLog SET PropStatus=@PropStatus WHERE Jhorderid = @Jhorderid")
.AddInputParameter("@PropStatus", DbType.Int32, )
.AddInputParameter("@Jhorderid", DbType.String, sporder_id)
.Execute();
Response.Clear();
Response.Write("success");
Response.End();
}
if (sta == "")
{
//更新订单状态为充值成功
DbSession.Default.FromSql(
@"UPDATE TOP(1) TPropLog SET PropStatus=@PropStatus WHERE Jhorderid = @Jhorderid")
.AddInputParameter("@PropStatus", DbType.Int32, )
.AddInputParameter("@Jhorderid", DbType.String, sporder_id)
.Execute();
Response.Clear();
Response.Write("success");
Response.End();
//更新订单状态为充值失败
} }

重点回顾:

1.JsonObject.DLL下载

2.签名顺序和字符要按照提供的做

3.回调地址要找客服设置

4.单个手机号每天有充值数量和次数的限制,超过次数会导致订单一直提示进行中,最后失败,失败也会有回调提示的

5.测试的时候可以将vs自带的iis调试工具配合ngrok映射到外网,这样直接就可以调试回调页面,改天我会写一个简单的教程,如何使用vs默认的iis映射到外网进行调试(微信的外网调试也可以这么做,非常方便哦)

最新文章

  1. Linux下用netstat查看网络状态、端口状态(转)
  2. 448. Find All Numbers Disappeared in an Array Add to List
  3. 水题 HDOJ 4727 The Number Off of FFF
  4. lua学习笔记
  5. Linux命令工具 top详解
  6. [kuangbin带你飞]专题十二 基础DP1
  7. 【学习笔记】【C语言】关键字
  8. Color About——First
  9. C++通过域名获取IP地址的方法;调试通过!
  10. Command Line-Version (SetACL.exe) – Syntax and Description
  11. javascript创建自定义对象和prototype
  12. lsof查看进程打开了哪些文件目录套接字
  13. Swift 简简单单实现手机九宫格手势密码解锁
  14. 扩展GridView实现无数据处理
  15. JAVA面向对象-----成员内部类的访问方式
  16. 个人 git-hub使用方法
  17. 单元测试-unittest
  18. dapper List SqlBulkCopy
  19. Windows环境下python的安装与使用
  20. 【DB2】关闭表的日志功能

热门文章

  1. CSS3(各UI元素状态伪类选择器受浏览器的支持情况)
  2. ssh forwarding 配置
  3. 我的arcgis培训照片13
  4. 【CV论文阅读】Detecting events and key actors in multi-person videos
  5. 【转】Golang 关于通道 Chan 详解
  6. 从epoll构建muduo-13 Reactor + ThreadPool 成型
  7. Mybatis的配置文件和映射文件具体解释
  8. hdu4057 Rescue the Rabbit(AC自己主动机+DP)
  9. JsonArray和JsonObject的使用
  10. 阿里云CentOS7.3搭建多用户私有git服务器(从安装git开始)