Xamarin.Android支付宝SDK Demo

来源:互联网 发布:同步推mac 编辑:程序博客网 时间:2024/05/20 04:15

废话不多说先上代码 这是Layout下布局代码 dll下载 http://download.csdn.net/detail/ccsdhs/9231817

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >


  <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical" >


    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center_vertical"
        android:orientation="horizontal" >


      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginRight="10dp"
          android:text="商品名称:"
          android:textColor="#777777"
          tools:ignore="HardcodedText" />


      <TextView
          android:id="@+id/product_subject"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="right"
          android:text="测试的商品"
          android:textColor="#333333"
          tools:ignore="HardcodedText" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center_vertical"
        android:orientation="horizontal" >


      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginRight="10dp"
          android:text="商品描述:"
          android:textColor="#777777"
          tools:ignore="HardcodedText" />


      <TextView
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="right"
          android:text="该测试商品的详细描述"
          android:textColor="#333333"
          tools:ignore="HardcodedText" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center_vertical"
        android:orientation="horizontal" >


      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginRight="10dp"
          android:text="商品价格:"
          android:textColor="#777777"
          tools:ignore="HardcodedText" />


      <TextView
          android:id="@+id/product_price"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="right"
          android:text="0.01元"
          android:textColor="#ff6600"
          tools:ignore="HardcodedText" />
    </LinearLayout>


    <Button
        android:id="@+id/pay"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:onClick="pay"
        android:text="支付"
        tools:ignore="HardcodedText" />


    <Button
        android:id="@+id/check"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:onClick="check"
        android:text="检查账户"
        tools:ignore="HardcodedText" />
  </LinearLayout>


</ScrollView>

这个是Activity 公钥私钥不明白的可以去看一下支付宝的文档

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.App;
using Android.Text;
using Android.Content;
using Java.Net;
using Java.IO;
using Com.Alipay.Sdk.App;
using Java.Text;
using Java.Util;
using Com.Alipay.Sdk.Pay.Demo;


namespace AlipayDemo
{
    [Activity(Label = "My Activity")]
    public class PayDemoActivity : FragmentActivity
    {
        private Button pay, check;
        private Context context;
        // 商户PID
        public static String PARTNER = "";
        // 商户收款账号
        public static String SELLER = "";
        // 商户私钥,pkcs8格式
        public static String RSA_PRIVATE = "";
        // 支付宝公钥
        public static String RSA_PUBLIC = "";
        
        private static int SDK_PAY_FLAG = 1;


        private static int SDK_CHECK_FLAG = 2;
        private Handler myHandler;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);


            // Create your application here
            SetContentView(Resource.Layout.pay);
            myHandler = new mHandler(this);
            pay = FindViewById<Button>(Resource.Id.pay);
            check = FindViewById<Button>(Resource.Id.check);
            pay.Click += new EventHandler(pay_Click);
            check.Click += new EventHandler(check_Click);
        }


        void check_Click(object sender, EventArgs e)
        {
            new Java.Lang.Thread(() =>
            {
                // 构造PayTask 对象
                PayTask payTask = new PayTask(this);
                // 调用查询接口,获取查询结果
                bool isExist = payTask.CheckAccountIfExist();


                Message msg = new Message();
                msg.What = SDK_CHECK_FLAG;
                msg.Obj = isExist;
                myHandler.SendMessage(msg);
            }).Start();
        }


        void pay_Click(object sender, EventArgs e)
        {
            if (TextUtils.IsEmpty(PARTNER) || TextUtils.IsEmpty(RSA_PRIVATE)
                || TextUtils.IsEmpty(SELLER))
            {
                new AlertDialog.Builder(this)
                        .SetTitle("警告")
                        .SetMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
                        .SetPositiveButton("确定",
                                new IDialogInterfaceListener(this)).Show();
                return;
            }
            // 订单
            String orderInfo = getOrderInfo("雅致观海一线海景房A3021", "1室1厅1卫", "13.23");


            // 对订单做RSA 签名
            String sign = signS(orderInfo);
            try
            {
                // 仅需对sign 做URL编码
                sign = URLEncoder.Encode(sign, "UTF-8");
            }
            catch (UnsupportedEncodingException ee)
            {
                ee.PrintStackTrace();
            }


            // 完整的符合支付宝参数规范的订单信息
            String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                    + getSignType();
            // 必须异步调用
            new Java.Lang.Thread(() =>
            {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(this);
                // 调用支付接口,获取支付结果
                String result = alipay.Pay(payInfo);


                Message msg = new Message();
                msg.What = SDK_PAY_FLAG;
                msg.Obj = result;
                myHandler.SendMessage(msg);
            }).Start();
        }
        public class mHandler : Handler
        {
            private Context context;
            public mHandler(Context contexts)
            {
                context = contexts;
            }
            public override void HandleMessage(Message msg)
            {
                switch (msg.What)
                {
                    case 1:
                        {
                            PayResult payResult = new PayResult((String)msg.Obj);


                            // 支付宝返回此次支付结果及加签,建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                            String resultInfo = payResult.Result;


                            String resultStatus = payResult.ResultStatus;


                            // 判断resultStatus 为“9000”则代表支付成功,具体状态码代表含义可参考接口文档
                            if (TextUtils.Equals(resultStatus, "9000"))
                            {
                                Toast.MakeText(context, "支付成功",
                                        ToastLength.Short).Show();
                            }
                            else
                            {
                                // 判断resultStatus 为非“9000”则代表可能支付失败
                                // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,最终交易是否成功以服务端异步通知为准(小概率状态)
                                if (TextUtils.Equals(resultStatus, "8000"))
                                {
                                    Toast.MakeText(context, "支付结果确认中",
                                            ToastLength.Short).Show();


                                }
                                else
                                {
                                    // 其他值就可以判断为支付失败,包括用户主动取消支付,或者系统返回的错误
                                    Toast.MakeText(context, "支付失败",
                                            ToastLength.Short).Show();


                                }
                            }
                            break;
                        }
                    case 2:
                        {
                            Toast.MakeText(context, "检查结果为:" + msg.Obj,
                                    ToastLength.Short).Show();
                            break;
                        }
                    default:
                        break;
                }
            }
        }
        //public void pay(View v)
        //{


            
        //}
        //public void check(View v)
        //{
            
        //}
        public void getSDKVersion()
        {
            PayTask payTask = new PayTask(this);
            String version = payTask.Version;
            Toast.MakeText(this, version, ToastLength.Short).Show();
        }
        public String getOrderInfo(String subject, String body, String price)
        {


            // 签约合作者身份ID
            String orderInfo = "partner=" + "\"" + PARTNER + "\"";


            // 签约卖家支付宝账号
            orderInfo += "&seller_id=" + "\"" + SELLER + "\"";


            // 商户网站唯一订单号
            orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";


            // 商品名称
            orderInfo += "&subject=" + "\"" + subject + "\"";


            // 商品详情
            orderInfo += "&body=" + "\"" + body + "\"";


            // 商品金额
            orderInfo += "&total_fee=" + "\"" + price + "\"";


            // 服务器异步通知页面路径
            orderInfo += "&notify_url=" + "\"" + "http://www.sihaiyoujia.com"
                    + "\"";


            // 服务接口名称, 固定值
            orderInfo += "&service=\"mobile.securitypay.pay\"";


            // 支付类型, 固定值
            orderInfo += "&payment_type=\"1\"";


            // 参数编码, 固定值
            orderInfo += "&_input_charset=\"utf-8\"";


            // 设置未付款交易的超时时间
            // 默认30分钟,一旦超时,该笔交易就会自动被关闭。
            // 取值范围:1m~15d。
            // m-分钟,h-小时,d-天,1c-当天(无论交易何时创建,都在0点关闭)。
            // 该参数数值不接受小数点,如1.5h,可转换为90m。
            orderInfo += "&it_b_pay=\"30m\"";


            // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
            // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";


            // 支付宝处理完请求后,当前页面跳转到商户指定页面的路径,可空
            orderInfo += "&return_url=\"m.alipay.com\"";


            // 调用银行卡支付,需配置此参数,参与签名, 固定值 (需要签约《无线银行卡快捷支付》才能使用)
            // orderInfo += "&paymethod=\"expressGateway\"";


            return orderInfo;
        }
        public String getOutTradeNo()
        {
            SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
                    Locale.Default);
            Date date = new Date();
            String key = format.Format(date);


            Java.Util.Random r = new Java.Util.Random();
            key = key + r.NextInt();
            key = key.Substring(0, 15);
            return key;
        }
        public String signS(String content)
        {
            return SignUtils.Sign(content, RSA_PRIVATE);
        }
        public String getSignType()
        {
            return "sign_type=\"RSA\"";
        }
        public class IDialogInterfaceListener : Java.Lang.Object, IDialogInterfaceOnClickListener
        {
            private Context context;
            public IDialogInterfaceListener(Context contexts)
            {
                context = contexts;
            }
            public void OnClick(IDialogInterface dialog, int which)
            {


            }
        }
    }
}

我的DLL中没有PayResult这个类 需要自己去写

using System;
using System.Collections.Generic;
using System.Text;
using Android.Text;


namespace AlipayDemo
{
    public class PayResult
    {
        private String resultStatus;
        private String result;
        private String memo;


        public PayResult(String rawResult)
        {


            if (TextUtils.IsEmpty(rawResult))
                return;


            String[] resultParams = rawResult.Split(';');
            foreach (String resultParam in resultParams)
            {
                if (resultParam.StartsWith("resultStatus"))
                {
                    resultStatus = gatValue(resultParam, "resultStatus");
                }
                if (resultParam.StartsWith("result"))
                {
                    result = gatValue(resultParam, "result");
                }
                if (resultParam.StartsWith("memo"))
                {
                    memo = gatValue(resultParam, "memo");
                }
            }
        }
        public override string ToString()
        {
            return "resultStatus={" + resultStatus + "};memo={" + memo + "};result={" + result + "}";
        }
        private String gatValue(String content, String key)
        {
            String prefix = key + "={";
            return content.Substring(content.IndexOf(prefix) + prefix.Length,
                    content.LastIndexOf("}"));
        }
        public String getResultStatus()
        {
            return resultStatus;
        }
        public String getMemo()
        {
            return memo;
        }
        public String getResult()
        {
            return result;
        }
    }
}

至此配置好支付宝那边网关公钥私钥问题就可以运行啦

0 0
原创粉丝点击