@Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.entry);

    // 通过WXAPIFactory工厂,获取IWXAPI的实例
    api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);

    payBtn = (Button) findViewById(R.id.goto_pay_btn);
    payBtn.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            startActivity(new Intent(WXEntryActivity.this, PayActivity.class));
            finish();
          }
        });

    // debug

    // debug end

    api.handleIntent(getIntent(), this);
  }
Esempio n. 2
0
  private void weixinPay() {
    String packge = "Sign=WXPay";
    api = WXAPIFactory.createWXAPI(this, WeixinConstants.APP_ID, true);
    req.appId = app_id;
    req.nonceStr = nonce_str;
    req.packageValue = packge;
    req.partnerId = mch_id;
    req.prepayId = prepay_id;
    req.timeStamp = timeStamp;

    List<NameValuePair> signParams = new LinkedList<NameValuePair>();
    signParams.add(new BasicNameValuePair("appid", req.appId));
    signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
    signParams.add(new BasicNameValuePair("package", req.packageValue));
    signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
    signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
    // signParams.add(new BasicNameValuePair("sign", sign));
    signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
    req.sign = genAppSign(signParams);
    if (dialog.isShowing()) {
      dialog.dismiss();
    }
    api.registerApp(WeixinConstants.APP_ID);
    api.sendReq(req);
    bt_pay.setEnabled(true);
  }
Esempio n. 3
0
  @Override
  public void onReceive(Context context, Intent intent) {
    final IWXAPI api = WXAPIFactory.createWXAPI(context, null);

    // 将该app注册到微信
    api.registerApp(Constants.APP_ID);
  }
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.pay_result);
   api = WXAPIFactory.createWXAPI(this, WXConstants.APP_ID_APP);
   api.handleIntent(getIntent(), this);
 }
Esempio n. 5
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_com);

    api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
    api.handleIntent(getIntent(), this);
  }
Esempio n. 6
0
  public boolean isUsableWX(Context context) {
    boolean isUsable = true;
    api = WXAPIFactory.createWXAPI(context, APP_WX_ID);
    api.registerApp(APP_WX_ID);
    if (api.isWXAppInstalled()) {}

    return isUsable;
  }
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   //        setContentView(R.layout.transparent_layout);
   user = new User();
   api = WXAPIFactory.createWXAPI(this, WeiXinConstants.APP_ID, false);
   api.handleIntent(getIntent(), this);
 }
  @Override
  public void initialize(CordovaInterface cordova, CordovaWebView webView) {

    instance = this;
    this.appId = getAppId();
    this.api = WXAPIFactory.createWXAPI(webView.getContext(), this.appId, true);
    this.api.registerApp(this.appId); // 将App注册到微信列表
  }
  @Override
  protected void onCreate(Bundle arg0) {
    // TODO Auto-generated method stub

    super.onCreate(arg0);
    setContentView(R.layout.activity_setting_bind);
    api = WXAPIFactory.createWXAPI(this, APP_ID, true);
    initWidget();
  }
Esempio n. 10
0
 @Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_weixin);
   tv = (TextView) findViewById(R.id.wx_res);
   // 通过WXAPIFactory工厂,获取IWXAPI的实例
   api = WXAPIFactory.createWXAPI(this, CommonConstants.WXAPP_ID, false);
   api.handleIntent(getIntent(), this);
 }
Esempio n. 11
0
 public static void WXImageShare(Context context, WXMediaMessage msg) {
   api = WXAPIFactory.createWXAPI(context, APP_WX_ID);
   api.registerApp(APP_WX_ID);
   if (api.isWXAppInstalled()) {
     SendMessageToWX.Req req = new SendMessageToWX.Req();
     req.transaction = buildTransaction("img");
     req.message = msg;
     req.scene = SendMessageToWX.Req.WXSceneSession;
     api.sendReq(req);
   } else {
     Toast.makeText(context, "您没有安装微信客户端,无法使用该功能!", Toast.LENGTH_LONG).show();
   }
 }
Esempio n. 12
0
  private void callPay(final WxOrderVO order) {
    final IWXAPI wxApi = WXAPIFactory.createWXAPI(ctx, GlobalConsts.WX_ID);
    wxApi.registerApp(GlobalConsts.WX_ID);

    PayReq req = new PayReq();
    req.appId = order.getAppid();
    req.partnerId = order.getPartnerid();
    req.prepayId = order.getPrepayid();
    req.packageValue = order.getPkg();
    req.nonceStr = order.getNoncestr();
    req.timeStamp = order.getTimestamp();
    req.sign = order.getSign();

    wxApi.sendReq(req);
  }
Esempio n. 13
0
 private void wechatLogin() {
   ShangXiang.wechatAPI = WXAPIFactory.createWXAPI(this, Consts.WECHAT_APPID, false);
   if (ShangXiang.wechatAPI.isWXAppInstalled() && ShangXiang.wechatAPI.isWXAppSupportAPI()) {
     Bundle bundle = new Bundle();
     bundle.putString("action", "login");
     Intent intent = new Intent(Login.this, WXEntryActivity.class);
     intent.putExtras(bundle);
     this.startActivity(intent);
   } else {
     Utils.Dialog(
         this,
         getString(R.string.dialog_normal_title),
         getString(R.string.dialog_login_need_wechat));
   }
 }
Esempio n. 14
0
  @Override
  protected void init() throws Exception {
    if (mIWXAPI == null) {
      mIWXAPI = WXAPIFactory.createWXAPI(getContext(), mAppId, true);
      if (mIWXAPI.isWXAppInstalled()) {
        mIWXAPI.registerApp(mAppId);
      }
    }

    if (!mIWXAPI.isWXAppInstalled()) {
      String msg = getContext().getString(R.string.bili_share_sdk_not_install_wechat);
      Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
      throw new ShareException(msg, BiliShareStatusCode.ST_CODE_SHARE_ERROR_NOT_INSTALL);
    }
  }
Esempio n. 15
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_book_info);
    api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
    Intent intent = getIntent();
    BOOKID = intent.getExtras().get("bookID").toString();
    BOOK_NAME = intent.getExtras().get("bookName").toString();
    BOOK_AUTHOR = intent.getExtras().get("bookAuthor").toString();
    BOOK_PUBLISHER = intent.getExtras().get("bookPublisher").toString();
    BOOK_CALL_NUMBER = intent.getExtras().get("bookCallNumber").toString();

    // 分享的书JSON信息
    shareBook = new JSONObject();
    try {
      shareBook.put("t", BOOK_NAME); // t:书名
      shareBook.put("a", BOOK_AUTHOR); // a:作者
      shareBook.put("p", BOOK_PUBLISHER); // p:出版社
      shareBook.put("c", BOOK_CALL_NUMBER); // c:索书号
    } catch (JSONException e) {
      e.printStackTrace();
      Log.d("VNA", "BookInfoActivity.class: JSON 基本信息出现错误");
    }

    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.book_content);

    dialog =
        new MaterialDialog.Builder(this)
            .title("加载馆藏中")
            .content("请稍候")
            .progress(true, 0)
            .autoDismiss(false)
            .show();

    initToolbar();
    initSwipeBack();
    initFab();

    collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    collapsingToolbarLayout.setTitle(BOOK_NAME);

    initRecyclerView();
  }
Esempio n. 16
0
  private void initview() {
    // TODO Auto-generated method stub
    txTitle = (TextView) findViewById(R.id.title);
    txTime = (TextView) findViewById(R.id.time);
    txFrom = (TextView) findViewById(R.id.from);
    tvSeenum = (TextView) findViewById(R.id.tv_newsdaly_seenum);

    back = (Button) findViewById(R.id.btn_back);
    btnShare = (Button) findViewById(R.id.btn_newsdayly_share);

    webView = (WebView) findViewById(R.id.webView1);
    layout_content = (LinearLayout) findViewById(R.id.ln_content);

    btn_newscommentadd = (Button) findViewById(R.id.btn_newsdalycomment_add);
    ed_newscomment = (EditText) findViewById(R.id.ed_newsdalycomment_comment);

    back.setOnClickListener(this);
    btn_newscommentadd.setOnClickListener(this);
    btnShare.setOnClickListener(this);

    txTitle.setText(getIntent().getStringExtra("title"));
    txTime.setText(getIntent().getStringExtra("time"));
    txFrom.setText(getIntent().getStringExtra("from"));
    tvSeenum.setText(getIntent().getStringExtra("seenum"));

    a = getIntent().getStringExtra("content");
    webView.loadDataWithBaseURL(null, a, "text/html", "UTF-8", null);
    webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    webView.getSettings().setDomStorageEnabled(true);

    // 微信注册
    api = WXAPIFactory.createWXAPI(this, APP_ID);
    api.registerApp(APP_ID);

    stitle = getIntent().getStringExtra("title");
    surl = getIntent().getStringExtra("url");
  }
Esempio n. 17
0
 private void initWxShare() {
   // 实例化
   wxApi = WXAPIFactory.createWXAPI(this, APP_ID);
   wxApi.registerApp(APP_ID);
 }
Esempio n. 18
0
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, true);
   api.handleIntent(getIntent(), this);
 }
Esempio n. 19
0
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   wxApi = WXAPIFactory.createWXAPI(this, AppConfig.WX_APP_ID, true);
   wxApi.handleIntent(getIntent(), this);
 }
/** @author 课程预定支付 */
public class LineTeachSelePlayActivity extends BaseActivity {
  public static LineTeachSelePlayActivity lineTeachSelePlayActivity;
  /** ** 向微信开放平台申请得到的appid、appsecret ** */
  public String APP_ID = "wxdc544db06a6449fc";
  /** 商户MCH_ID ** */
  public String MCH_ID = "1245101302";
  /** ** 商户秘钥 *** */
  public String API_KEY = "Koill624lDdg4BGId15KW1v59L0Qq1cg";

  // ==2跳转到商品订单的页面
  public static final String PLAY_STAT_01 = "3";
  // ==WX支付方式
  public static final String PLAY_STAT = "WX";

  private PayReq req;
  private final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
  private Map<String, String> resultunifiedorder;
  private StringBuffer sb;

  /** ******************* 微信支付 *********************** */
  public static final String PARTNER = "2088021262905342";
  // 商户收款账号
  public static final String SELLER = "*****@*****.**";
  // 商户私钥,pkcs8格式
  public static final String RSA_PRIVATE =
      "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKL1vc8TFyZic/be8xIq59bx2zgBobbSKmREZE6E9F0cx33qv3pPYeoqc0lArXMD/I6Lt0AYJKsicy48uXJRDBhXu9QDPsd+Wj0GwLJaczDdMQDi3tNdZZ3MFgGUUM2LT6+UbNyzYPGne3LqsM7mEITtVGKYAMCrdWmeSybbz2h9AgMBAAECgYB6SGEINFEY0qQmSiKoLV4PYymXG1JYN9jrqI6EhSxBeskP6cmJZGwbJYOhIlGFjyZDaQA3rmZFrPI1bgfSipLBtvn3PBPTwP303mlmQId3vqLEKoWaf9fTA7gt83SQvVAE8s0DJYrlBikAkcHeZ0uBJolcQP6esi4FMzYIIiuLWQJBAM084Kb/wnhv0kSOgs/8jn2v+0k58GfcGDrpSqnTcYKKXImMpkRknfw/32QZPy8lEk8D3azpVUTYimPIqRYEEOsCQQDLQ/BnQXJAstfNmvMivQ3OJrDDajQ18F5/Eugu+LsRZc+g6UfxNU3dR25H9MrgBgEYTKcN/tx45sYMRxwFbdI3AkAmn1czdhv1qC1so1jwpPl3o59pR1L7aIrSw0Y+sUDCLSF+7Q34/upQJwD2CF5Ak/xfDD4yJPLb8tgQMRnIv9kjAkEAvD0KoVUGjcwR9iKND5qs8kD6ab4s49babCwCQZ2vAAmdIpNnQIXwuf+wrYqRZq2ozewOuPNREdYFitE/rfdqOQJBAI2Dv7w4fVXNvh2Z3XjsK4qMAPMfq1xD6E9EbNJv/hKqbbZVcWK6vUfrU2wQtBUzGWwhlFiMtBMr19tBd1QyqNU=";
  // 支付宝公钥
  public static final String RSA_PUBLIC =
      "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCi9b3PExcmYnP23vMSKufW8ds4AaG20ipkRGROhPRdHMd96r96T2HqKnNJQK1zA/yOi7dAGCSrInMuPLlyUQwYV7vUAz7Hflo9BsCyWnMw3TEA4t7TXWWdzBYBlFDNi0+vlGzcs2Dxp3ty6rDO5hCE7VRimADAq3Vpnksm289ofQIDAQAB";

  /** ************ 支付 ***** */
  private RelativeLayout zhifuRelativeLayout, zhifuRelativeLayout2;

  private OrderBean orderBean;
  public final String RESULTStatus = "9000";
  public final String RESULTStatus_FINSH = "8000";

  // 支付宝支付
  public final int PLAY_ZH = 2;

  // 微信支付
  public final int PLAY_WX = 3;
  /** *** 支付返回支付状态 */
  @SuppressLint("HandlerLeak")
  private Handler mHandler =
      new Handler() {
        @Override
        public void handleMessage(Message msg) {
          switch (msg.what) {
            case 1:
              if (msg.obj != null) {
                PayResult payResult = new PayResult((String) msg.obj);
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为“9000”则代表支付成功,具体状态码代表含义可参考接口文档
                if (TextUtils.equals(resultStatus, RESULTStatus)) {
                  Toast.makeText(
                          LineTeachSelePlayActivity.this,
                          getResources().getString(R.string.mark_play_st_sess),
                          Toast.LENGTH_SHORT)
                      .show();
                  Intent intent =
                      new Intent(LineTeachSelePlayActivity.this, LineTeachOrderActivity.class);
                  intent.putExtra("TYPE", PLAY_ZH);
                  startActivity(intent);
                  finish();
                } else {
                  // 判断resultStatus 为非“9000”则代表可能支付失败
                  // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,最终交易是否成功以服务端异步通知为准(小概率状态)
                  if (TextUtils.equals(resultStatus, RESULTStatus_FINSH)) {
                    Toast.makeText(
                            LineTeachSelePlayActivity.this,
                            getResources().getString(R.string.mark_play_st_sure),
                            Toast.LENGTH_SHORT)
                        .show();

                  } else {
                    // 其他值就可以判断为支付失败,包括用户主动取消支付,或者系统返回的错误
                    Toast.makeText(
                            LineTeachSelePlayActivity.this,
                            getResources().getString(R.string.mark_play_st_fail),
                            Toast.LENGTH_SHORT)
                        .show();
                  }
                }
              }

              break;
          }
        }
      };

  private OnClickListener mClickListener =
      new OnClickListener() {

        @Override
        public void onClick(View v) {

          switch (v.getId()) {

              // 支付宝支付
            case R.id.zhufu_rel_01:
              boolean connectInternet =
                  NetworkStateUtil.isConnectInternet(LineTeachSelePlayActivity.this);
              if (!connectInternet) {
                WidgetUtil.ToastMessage(
                    LineTeachSelePlayActivity.this,
                    getResources().getString(R.string.connect_net_fail));
                return;
              } else {
                // 2代表支付宝支付
                PostOrderId(orderBean, PLAY_ZH);
                Payment(orderBean);
              }

              break;
              // 微信支付

            case R.id.zhufu_rel_02:
              boolean connectInternet1 =
                  NetworkStateUtil.isConnectInternet(LineTeachSelePlayActivity.this);
              if (!connectInternet1) {
                WidgetUtil.ToastMessage(
                    LineTeachSelePlayActivity.this,
                    getResources().getString(R.string.connect_net_fail));
                return;
              } else {

                if (!msgApi.isWXAppInstalled()) {

                  toastLong("您还没有安装微信!");
                  // 提醒用户没有按照微信
                  return;
                } else {
                  // 3代表微信支付
                  PostOrderId(orderBean, PLAY_WX);
                  WeiXinPlay(orderBean);
                }
              }

              break;
          }
        }
      };

  @Override
  protected int setContentView() {
    lineTeachSelePlayActivity = this;
    return R.layout.activity_markplay;
  }

  @Override
  public void initView() {
    clickLeft_iv(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            Intent intent =
                new Intent(LineTeachSelePlayActivity.this, LineTeachOrderActivity.class);
            intent.putExtra("TYPE", PLAY_ZH);
            startActivity(intent);
            finish();
          }
        });

    req = new PayReq();
    sb = new StringBuffer();
    msgApi.registerApp(APP_ID);
    /** ************ 微信支付 ************* */
    setTitle(R.string.golfs_marktitle_06);

    /** 获取传递过来的支付对象 * */
    Intent intent = getIntent();
    orderBean = (OrderBean) intent.getSerializableExtra("orderbean");

    // 支付金额
    aQuery.id(R.id.play_mark).text(getString(R.string.golfs_money) + orderBean.goodsAmount);

    /** ** 支付方式 **** */
    zhifuRelativeLayout = (RelativeLayout) findViewById(R.id.zhufu_rel_01);
    zhifuRelativeLayout2 = (RelativeLayout) findViewById(R.id.zhufu_rel_02);
    zhifuRelativeLayout.setOnClickListener(mClickListener);
    zhifuRelativeLayout2.setOnClickListener(mClickListener);
  }

  /** 去付款 */
  public void Payment(OrderBean orderBean) {

    // 订单
    String orderInfo =
        getOrderInfo(
            orderBean.goodsName, orderBean.goodsAttr, orderBean.orderSn, orderBean.orderAmount);

    // 对订单做RSA 签名
    String sign = sign(orderInfo);

    try {
      // 仅需对sign 做URL编码
      sign = URLEncoder.encode(sign, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    // 完整的符合支付宝参数规范的订单信息
    final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();
    Runnable payRunnable =
        new Runnable() {

          @Override
          public void run() {
            // 构造PayTask 对象
            PayTask alipay = new PayTask(LineTeachSelePlayActivity.this);
            // 调用支付接口,获取支付结果
            String result = alipay.pay(payInfo);

            if (result != null && result.length() > 0) {
              Message msg = new Message();
              msg.what = 1;
              msg.obj = result;
              mHandler.sendMessage(msg);
            }
          }
        };

    // 必须异步调用
    Thread payThread = new Thread(payRunnable);
    payThread.start();
  }

  /** get the sdk version. 获取SDK版本号 */
  public void getSDKVersion() {
    PayTask payTask = new PayTask(this);
    String version = payTask.getVersion();
    Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
  }

  /** create the order info. 创建订单信息 */
  public String getOrderInfo(String subject, String body, String out_trade_no, Double price) {
    // 签约合作者身份ID****
    String orderInfo = "partner=" + "\"" + PARTNER + "\"";

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

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

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

    if (body != null && body.length() > 0) {
      orderInfo += "&body=" + "\"" + body + "\"";
    } else {
      orderInfo += "&body=" + "\"" + "无商品属性" + "\"";
    }
    // 商品金额*****
    orderInfo += "&total_fee=" + "\"" + price + "\"";

    // 服务器异步通知页面路径
    orderInfo +=
        "&notify_url="
            + "\""
            + ResourceConfigManager.RELEASE_DOMAIN_HOST
            + "/order/alipay_notify"
            + "\"";

    // 服务接口名称, 固定值
    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=\"1d\"";

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

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

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

    return orderInfo;
  }

  /**
   * sign the order info. 对订单信息进行签名
   *
   * @param content 待签名订单信息
   */
  public String sign(String content) {
    return SignUtils.sign(content, RSA_PRIVATE);
  }

  /** get the sign type we use. 获取签名方式 */
  public String getSignType() {
    return "sign_type=\"RSA\"";
  }

  /** ****************************************** 微信支付 *************************** */

  /**
   * 微信支付
   *
   * @param orderBean
   */
  public void WeiXinPlay(OrderBean orderBean) {
    GetPrepayIdTask getPrepayId = new GetPrepayIdTask(orderBean);
    getPrepayId.execute();
  }

  private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {
    private OrderBean orderBean;

    private ProgressDialog dialog;

    public GetPrepayIdTask(OrderBean orderBean) {
      this.orderBean = orderBean;
    }

    @Override
    protected void onPreExecute() {
      dialog =
          ProgressDialog.show(
              LineTeachSelePlayActivity.this,
              getString(R.string.app_tip),
              getString(R.string.getting_prepayid));
    }

    @Override
    protected void onPostExecute(Map<String, String> result) {
      if (dialog != null) {
        dialog.dismiss();
      }
      sb.append("prepay_id\n" + result.get("prepay_id") + "\n\n");
      resultunifiedorder = result;
      Log.e("jjjjjjj:::::", "result:" + result.get("return_code"));
      if (result.get("return_code").equals("SUCCESS")) {
        genPayReq();
      } else {

        WidgetUtil.ToastMessage(
            LineTeachSelePlayActivity.this, getString(R.string.mark_play_st_fail));
        return;
      }
    }

    @Override
    protected void onCancelled() {
      super.onCancelled();
    }

    @Override
    protected Map<String, String> doInBackground(Void... params) {

      String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
      String entity = genProductArgs(orderBean);

      Log.e("orion*******************", entity);

      byte[] buf = Util.httpPost(url, entity);

      String content = new String(buf);
      Log.e("orion********************", content);
      Map<String, String> xml = decodeXml(content);

      return xml;
    }
  }

  private String genAppSign(List<NameValuePair> params) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < params.size(); i++) {
      sb.append(params.get(i).getName());
      sb.append('=');
      sb.append(params.get(i).getValue());
      sb.append('&');
    }
    sb.append("key=");
    sb.append(API_KEY);

    this.sb.append("sign str\n" + sb.toString() + "\n\n");
    String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
    Log.e("orion", appSign);
    return appSign;
  }

  public Map<String, String> decodeXml(String content) {

    try {
      Map<String, String> xml = new HashMap<String, String>();
      XmlPullParser parser = Xml.newPullParser();
      parser.setInput(new StringReader(content));
      int event = parser.getEventType();
      while (event != XmlPullParser.END_DOCUMENT) {

        String nodeName = parser.getName();
        switch (event) {
          case XmlPullParser.START_DOCUMENT:
            break;
          case XmlPullParser.START_TAG:
            if ("xml".equals(nodeName) == false) {
              // 实例化student对象
              xml.put(nodeName, parser.nextText());
            }
            break;
          case XmlPullParser.END_TAG:
            break;
        }
        event = parser.next();
      }

      return xml;
    } catch (Exception e) {
      Log.e("orion", e.toString());
    }
    return null;
  }

  private String genNonceStr() {
    Random random = new Random();
    return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
  }

  private long genTimeStamp() {
    return System.currentTimeMillis() / 1000;
  }

  //
  private String genProductArgs(OrderBean orderBean) {
    int money = (int) (orderBean.orderAmount * 100);
    StringBuffer xml = new StringBuffer();

    try {
      String nonceStr = genNonceStr();

      xml.append("</xml>");
      Log.e("商户订单*****", "out_trade_no:" + orderBean.orderSn);
      List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
      packageParams.add(new BasicNameValuePair("appid", APP_ID));
      packageParams.add(new BasicNameValuePair("body", orderBean.goodsName));
      packageParams.add(new BasicNameValuePair("input_charset", "UTF-8"));
      packageParams.add(new BasicNameValuePair("mch_id", MCH_ID));
      packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
      // 服务器异步通知页面路径String.valueOf(orderBean.orderAmount)
      packageParams.add(
          new BasicNameValuePair(
              "notify_url", ResourceConfigManager.RELEASE_DOMAIN_HOST + "/order/weixin_notify"));
      packageParams.add(new BasicNameValuePair("out_trade_no", orderBean.orderSn));
      packageParams.add(new BasicNameValuePair("spbill_create_ip", "127.0.0.1"));
      packageParams.add(new BasicNameValuePair("total_fee", money + ""));
      packageParams.add(new BasicNameValuePair("trade_type", "APP"));

      String sign = genPackageSign(packageParams);
      packageParams.add(new BasicNameValuePair("sign", sign));

      String xmlstring = toXml(packageParams);

      return new String(xmlstring.toString().getBytes(), "ISO8859-1");

    } catch (Exception e) {
      Log.e("log****************", "genProductArgs fail, ex = " + e.getMessage());
      return null;
    }
  }

  private String toXml(List<NameValuePair> params) {
    StringBuilder sb = new StringBuilder();
    sb.append("<xml>");
    for (int i = 0; i < params.size(); i++) {
      sb.append("<" + params.get(i).getName() + ">");

      sb.append(params.get(i).getValue());
      sb.append("</" + params.get(i).getName() + ">");
    }
    sb.append("</xml>");

    Log.e("orion", sb.toString());
    return sb.toString();
  }

  /** 生成签名 */
  private String genPackageSign(List<NameValuePair> params) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < params.size(); i++) {
      sb.append(params.get(i).getName());
      sb.append('=');
      sb.append(params.get(i).getValue());
      sb.append('&');
    }
    sb.append("key=");
    sb.append(API_KEY);

    String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
    Log.e("orion", packageSign);
    return packageSign;
  }

  private void genPayReq() {

    req.appId = APP_ID;
    req.partnerId = MCH_ID;
    req.prepayId = resultunifiedorder.get("prepay_id");
    req.packageValue = "Sign=WXPay";
    req.nonceStr = genNonceStr();
    req.timeStamp = String.valueOf(genTimeStamp());
    List<NameValuePair> signParams = new LinkedList<NameValuePair>();
    signParams.add(new BasicNameValuePair("appid", req.appId));
    signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
    signParams.add(new BasicNameValuePair("package", req.packageValue));
    signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
    signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
    signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
    req.sign = genAppSign(signParams);
    sb.append("sign\n" + req.sign + "\n\n");

    sendPayReq();
  }

  private void sendPayReq() {
    WXPayEntryActivity.handler.sendEmptyMessage(2);
    msgApi.registerApp(APP_ID);
    msgApi.sendReq(req);
  }

  /** ** 提交支付方式 *** */
  private void PostOrderId(OrderBean orderBean, int payType) {
    final FinalHttp fh = new FinalHttp();
    fh.addHeader("Cookie", ParserUtil.getCookieValue(PreferencesUtil.getAuthToken()));
    AjaxParams ajaxParams = new AjaxParams();
    ajaxParams.put("orderId", orderBean.orderId + "");
    ajaxParams.put("payType", payType + "");

    fh.post(
        ResourceConfigManager.RELEASE_DOMAIN_HOST + "/order/updatePayType",
        ajaxParams,
        new AjaxCallBack<String>() {

          @Override
          public void onSuccess(String json) {
            Log.e("提交支付方式", "json:" + json);
          }

          @Override
          public void onFailure(Throwable t, int errorNo, String strMsg) {
            Log.e("提交失败", "json:" + errorNo);
          }
        });
  }

  @Override
  public void setListener() {}

  @Override
  public void getJSONByVolley(boolean isRefresh) {}
}
Esempio n. 21
0
 /** 分享朋友圈 */
 private void shareToFriendQuan(
     Context mcontext, String shareUrl, String title, String des, Drawable mDrawable, int type) {
   Bitmap b = null;
   ByteArrayOutputStream output = null;
   try {
     IWXAPI api = WXAPIFactory.createWXAPI(act, APP_ID);
     api.registerApp(APP_ID);
     WXMediaMessage msg = null;
     if (!api.isWXAppInstalled()) {
       Toast.makeText(
               act,
               act.getResources().getString(R.string.weixinsdk_demo_has_not_installed_weibo),
               Toast.LENGTH_SHORT)
           .show();
       return;
     }
     switch (type) {
       case Share_Text_Type:
         WXTextObject textObj = new WXTextObject();
         textObj.text = title;
         msg = new WXMediaMessage();
         msg.mediaObject = textObj;
         msg.description = title;
         break;
       case Share_Webpage_Type:
         WXWebpageObject webpage = new WXWebpageObject();
         webpage.webpageUrl = shareUrl;
         msg = new WXMediaMessage(webpage);
         msg.title = title;
         msg.description = des;
         break;
     }
     if (type == Share_Webpage_Type && mDrawable != null) {
       BitmapDrawable bitmapDrawable = (BitmapDrawable) mDrawable;
       b = bitmapDrawable.getBitmap();
       if (b == null) {
         bitmapDrawable =
             ((BitmapDrawable) context.getResources().getDrawable(R.drawable.ic_launcher));
         b = bitmapDrawable.getBitmap();
       }
       output = new ByteArrayOutputStream();
       b = zoomImg(b, 100);
       b.compress(CompressFormat.PNG, 70, output);
       byte[] result = output.toByteArray();
       msg.thumbData = result;
     }
     SendMessageToWX.Req req = new SendMessageToWX.Req();
     if (type == Share_Text_Type) req.transaction = buildTransaction("text");
     else if (type == Share_Webpage_Type) req.transaction = buildTransaction("webpage");
     req.message = msg;
     req.scene = SendMessageToWX.Req.WXSceneTimeline;
     api.sendReq(req);
   } catch (Exception e) {
     Toast.makeText(mcontext, mcontext.getString(R.string.share_weixin), 300).show();
   } finally {
     if (b != null) {
       b = null;
     }
     if (output != null) {
       try {
         output.close();
       } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
     }
   }
 }
Esempio n. 22
0
/**
 * @ClassName RechargeActivity @Description TODO 充值
 *
 * @author 李苜菲
 * @date 2015-8-27 下午2:20:26
 */
public class RechargeActivity extends BaseActivity implements OnClickListener {

  private EditText editText_pay_money;
  private Button button_pay;

  private String money = "";
  private eDaoClientApplication application = null;
  private ProgressDialog progressDialog;
  private Gson gson = new Gson();
  private MessageBox_YES box_YES;
  private String orderId = "";
  private PayReq req;
  final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
  private Map<String, String> resultunifiedorder;
  public static RechargeActivity instance;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO 自动生成的方法存根
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recharge);
    // 实现沉浸式状态栏效果
    setImmerseLayout(findViewById(R.id.navigation_fragment));
    application = (eDaoClientApplication) getApplication();
    instance = this;
    init();
    weixin();
  }

  private void init() {
    // TODO 自动生成的方法存根
    editText_pay_money = (EditText) findViewById(R.id.recharge_editText_pay_money);

    button_pay = (Button) findViewById(R.id.recharge_btn_pay);

    button_pay.setOnClickListener(this);
  }

  private void weixin() {
    // TODO 自动生成的方法存根
    req = new PayReq();
    msgApi.registerApp(Constants.APP_ID);
  }

  @Override
  public void onClick(View v) {
    // TODO 自动生成的方法存根
    switch (v.getId()) {
      case R.id.recharge_btn_pay:
        if (checkInput()) {
          confirm();
        }
        break;
    }
  }

  private boolean checkInput() {
    // TODO 自动生成的方法存根
    money = editText_pay_money.getText().toString().trim();
    if (TextUtils.isEmpty(money)) {
      Utity.showToast(getApplicationContext(), "请输入金额");
      return false;
    }
    return true;
  }

  private void confirm() {
    // TODO 自动生成的方法存根
    Map<String, String> data = new HashMap<String, String>();
    data.put("bizName", "50000");
    data.put("method", "50009");
    data.put("fromUserId", application.getUserId());
    data.put("payFee", money);

    showProgressDialog("提交中...");
    HttpUtil.SendPostRequest(
        gson.toJson(data),
        eDaoClientConfig.url,
        new HttpCallbackListener() {

          @Override
          public void onFinish(final ResponseData responseData) {
            // TODO 自动生成的方法存根
            runOnUiThread(
                new Runnable() {

                  @Override
                  public void run() {
                    // TODO 自动生成的方法存根
                    if (responseData.getRsCode() != 1) {
                      closeProgressDialog();
                      box_YES = new MessageBox_YES(RechargeActivity.this);
                      box_YES.showDialog(responseData.getMsg(), null);
                    } else {
                      try {
                        JSONObject result = new JSONObject(responseData.getJsonData().toString());
                        orderId = result.getString("ordersId");
                        GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
                        getPrepayId.execute();
                      } catch (JSONException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                      }
                    }
                  }
                });
          }

          @Override
          public void onError(Exception e) {
            // TODO 自动生成的方法存根
            runOnUiThread(
                new Runnable() {
                  @Override
                  public void run() {
                    // TODO 自动生成的方法存根
                    closeProgressDialog();
                  }
                });
          }
        });
  }

  private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onPostExecute(Map<String, String> result) {
      resultunifiedorder = result;
      System.out.println("onPostExecute resultunifiedorder:" + resultunifiedorder);
      genPayReq();
      sendPayReq();
    }

    @Override
    protected void onCancelled() {
      super.onCancelled();
    }

    @Override
    protected Map<String, String> doInBackground(Void... params) {
      System.out.println("doInBackground");
      String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
      String entity = genProductArgs();

      Log.e("orion", entity);

      byte[] buf = Util.httpPost(url, entity);
      String content = new String(buf);
      System.out.println("微信返回:" + content);
      Map<String, String> xml = decodeXml(content);

      return xml;
    }
  }

  private void sendPayReq() {
    msgApi.registerApp(Constants.APP_ID);
    msgApi.sendReq(req);
  }

  private String genProductArgs() {
    StringBuffer xml = new StringBuffer();

    try {
      String nonceStr = genNonceStr();

      xml.append("</xml>");
      List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
      packageParams.add(new BasicNameValuePair("appid", Constants.APP_ID));
      packageParams.add(new BasicNameValuePair("body", "充值"));
      packageParams.add(new BasicNameValuePair("mch_id", Constants.MCH_ID));
      packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
      packageParams.add(new BasicNameValuePair("notify_url", eDaoClientConfig.wxReUrl));
      packageParams.add(new BasicNameValuePair("out_trade_no", orderId));
      packageParams.add(new BasicNameValuePair("spbill_create_ip", Utity.getLocalHostIp()));
      Double fee = Double.parseDouble(money) * 100;
      packageParams.add(
          new BasicNameValuePair(
              "total_fee", String.valueOf(Utity.subZeroAndDot(String.valueOf(fee)))));
      packageParams.add(new BasicNameValuePair("trade_type", "APP"));

      String sign = genPackageSign(packageParams);
      packageParams.add(new BasicNameValuePair("sign", sign));

      String xmlstring = toXml(packageParams);
      xmlstring = new String(xmlstring.getBytes("UTF-8"), "ISO-8859-1");

      return xmlstring;

    } catch (Exception e) {
      System.out.println("genProductArgs异常" + e.getMessage());
      return null;
    }
  }

  private String genPackageSign(List<NameValuePair> params) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < params.size(); i++) {
      sb.append(params.get(i).getName());
      sb.append('=');
      sb.append(params.get(i).getValue());
      sb.append('&');
    }
    sb.append("key=");
    sb.append(Constants.API_KEY);

    String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
    Log.e("orion", packageSign);
    return packageSign;
  }

  private String genAppSign(List<NameValuePair> params) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < params.size(); i++) {
      sb.append(params.get(i).getName());
      sb.append('=');
      sb.append(params.get(i).getValue());
      sb.append('&');
    }
    sb.append("key=");
    sb.append(Constants.API_KEY);

    String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
    Log.e("orion", appSign);
    return appSign;
  }

  public Map<String, String> decodeXml(String content) {

    try {
      Map<String, String> xml = new HashMap<String, String>();
      XmlPullParser parser = Xml.newPullParser();
      parser.setInput(new StringReader(content));
      int event = parser.getEventType();
      while (event != XmlPullParser.END_DOCUMENT) {

        String nodeName = parser.getName();
        switch (event) {
          case XmlPullParser.START_DOCUMENT:
            break;
          case XmlPullParser.START_TAG:
            if ("xml".equals(nodeName) == false) {
              // 实例化student对象
              xml.put(nodeName, parser.nextText());
            }
            break;
          case XmlPullParser.END_TAG:
            break;
        }
        event = parser.next();
      }

      return xml;
    } catch (Exception e) {
      Log.e("orion", e.toString());
    }
    return null;
  }

  private String toXml(List<NameValuePair> params) {
    StringBuilder sb = new StringBuilder();
    sb.append("<xml>");
    for (int i = 0; i < params.size(); i++) {
      sb.append("<" + params.get(i).getName() + ">");

      sb.append(params.get(i).getValue());
      sb.append("</" + params.get(i).getName() + ">");
    }
    sb.append("</xml>");

    Log.e("orion", sb.toString());
    return sb.toString();
  }

  private String genNonceStr() {
    Random random = new Random();
    return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
  }

  private long genTimeStamp() {
    return System.currentTimeMillis() / 1000;
  }

  private void genPayReq() {

    req.appId = Constants.APP_ID;
    req.partnerId = Constants.MCH_ID;
    req.prepayId = resultunifiedorder.get("prepay_id");
    req.packageValue = "Sign=WXPay";
    req.nonceStr = genNonceStr();
    req.timeStamp = String.valueOf(genTimeStamp());

    List<NameValuePair> signParams = new LinkedList<NameValuePair>();
    signParams.add(new BasicNameValuePair("appid", req.appId));
    signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
    signParams.add(new BasicNameValuePair("package", req.packageValue));
    signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
    signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
    signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

    req.sign = genAppSign(signParams);

    Log.e("orion", signParams.toString());
  }
}
  @SuppressLint("SetJavaScriptEnabled")
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.publics_webview);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    try {
      if (getIntent().hasExtra("internal")) {
        isInternal = getIntent().getStringExtra("internal").equals("1");
      }
    } catch (Exception e) {
      isInternal = false;
    }

    // 微信注册
    api = WXAPIFactory.createWXAPI(this, appId, false);
    api.registerApp(appId);

    url = this.getIntent().getStringExtra("url");
    String title = "";
    if (getIntent().hasExtra("from")) {
      title = "历史消息";
      if (getIntent().hasExtra("marker")) {
        title = getIntent().getStringExtra("marker"); // 来自工作圈跳转
        // Social_WorkGroupListAdapter
        String id = getIntent().getStringExtra("id"); // 来自工作圈跳转
        String pic = getIntent().getStringExtra("img");
        String msgTitle = getIntent().getStringExtra("msgtitle");
        String cnname = getIntent().getStringExtra("cnname");
        if (pic.contains(Pub_HttpUtils.BASE_URL)) {
          pic = pic.replace(Pub_HttpUtils.BASE_URL, "");
        }

        msgData = new Pub_MenuContent();
        msgData.setId(id);
        msgData.setPic(pic);
        msgData.setTitle(msgTitle);
        msgData.setName(cnname);
      }
    } else {
      title = getIntent().getStringExtra("title");
      if (getIntent().hasExtra("specialMsg")) {
        Pub_message msg = (Pub_message) getIntent().getSerializableExtra("specialMsg");
        if (msg != null) {
          msgData = new Pub_MenuContent();
          msgData.setId(msg.getId());
          msgData.setPic("");
          msgData.setTitle("网页链接");
          msgData.setName("");
        }
      } else if (getIntent().hasExtra("fromMenu")) { // 菜单跳转
        msgData = new Pub_MenuContent();
        msgData.setId("0x123");
        msgData.setPic("");
        msgData.setTitle("网页链接");
        msgData.setName("");
      } else {
        msgData = (Pub_MenuContent) getIntent().getSerializableExtra("msg");
      }
    }

    text = (TextView) findViewById(R.id.textview_title);
    TextView share = (TextView) findViewById(R.id.shareBtn);
    text.setText(title);
    findViewById(R.id.button_left_1)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                IntentAnimUtil.backword(Pub_WebViewActivity.this);
              }
            });

    if (title.equals("历史消息")) {
      share.setVisibility(View.GONE);
    } else {
      share.setVisibility(View.VISIBLE);
      share.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              // TODO 分享到工作圈
              SharePopupWindow window = new SharePopupWindow(Pub_WebViewActivity.this);
              window.showAtLocation(
                  findViewById(R.id.public_root_view),
                  Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,
                  0,
                  0);
              // ActionSheet.createBuilder(Pub_WebViewActivity.this,
              // getSupportFragmentManager())
              // .setCancelButtonTitle("取 消")
              // .setOtherButtonTitles("分享到海航圈", "分享给好友" , "分享到微信朋友圈",
              // "分享给微信好友")
              // .setCancelableOnTouchOutside(true)
              // .setListener(Pub_WebViewActivity.this)
              // .show();
            }
          });
    }

    webview = (WebView) findViewById(R.id.webview);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setBuiltInZoomControls(true);
    webview.getSettings().setUseWideViewPort(true);
    webview.getSettings().setSupportZoom(true);
    webview.getSettings().setLoadWithOverviewMode(true);
    webview.getSettings().setDefaultTextEncodingName("UTF-8");
    webview.setWebViewClient(
        new WebViewClient() {
          @Override
          public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
              if (url.startsWith("hnairpublic")) {
                String user = url.substring(url.indexOf("=") + 1, url.length());
                Intent intent =
                    new Intent(Pub_WebViewActivity.this, Pub_OfficialAccountInfoActivity.class);
                intent.putExtra("user", user);
                IntentAnimUtil.startActivityWithSlideForward(
                    Pub_WebViewActivity.this, intent, false);
                return true;
              }
              String fileClass = url.substring(url.lastIndexOf(".") + 1);
              if (fileClass.equalsIgnoreCase("apk")) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                startActivity(intent);
                return true;
              }
            } catch (Exception e) {
              webview.loadUrl(url);
              return true;
            }
            webview.loadUrl(url);
            return true;
          }
        });
    webview.loadUrl(url);
  }
Esempio n. 24
0
public class PayActivity extends Activity {

  private static final String TAG = "MicroMsg.SDKSample.PayActivity";

  PayReq req;
  final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
  TextView show;
  Map<String, String> resultunifiedorder;
  StringBuffer sb;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pay);
    show = (TextView) findViewById(R.id.editText_prepay_id);
    req = new PayReq();
    sb = new StringBuffer();

    msgApi.registerApp(Constants.APP_ID);
    // 生成prepay_id
    Button payBtn = (Button) findViewById(R.id.unifiedorder_btn);
    payBtn.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
            getPrepayId.execute();
          }
        });
    Button appayBtn = (Button) findViewById(R.id.appay_btn);
    appayBtn.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            sendPayReq();
          }
        });

    // 生成签名参数
    Button appay_pre_btn = (Button) findViewById(R.id.appay_pre_btn);
    appay_pre_btn.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            genPayReq();
          }
        });

    String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
  }

  /** 生成签名 */
  private String genPackageSign(List<NameValuePair> params) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < params.size(); i++) {
      sb.append(params.get(i).getName());
      sb.append('=');
      sb.append(params.get(i).getValue());
      sb.append('&');
    }
    sb.append("key=");
    sb.append(Constants.API_KEY);

    String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
    Log.e("orion", packageSign);
    return packageSign;
  }

  private String genAppSign(List<NameValuePair> params) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < params.size(); i++) {
      sb.append(params.get(i).getName());
      sb.append('=');
      sb.append(params.get(i).getValue());
      sb.append('&');
    }
    sb.append("key=");
    sb.append(Constants.API_KEY);

    this.sb.append("sign str\n" + sb.toString() + "\n\n");
    String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
    Log.e("orion", appSign);
    return appSign;
  }

  private String toXml(List<NameValuePair> params) {
    StringBuilder sb = new StringBuilder();
    sb.append("<xml>");
    for (int i = 0; i < params.size(); i++) {
      sb.append("<" + params.get(i).getName() + ">");

      sb.append(params.get(i).getValue());
      sb.append("</" + params.get(i).getName() + ">");
    }
    sb.append("</xml>");

    Log.e("orion", sb.toString());
    return sb.toString();
  }

  private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {

    private ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
      dialog =
          ProgressDialog.show(
              PayActivity.this, getString(R.string.app_tip), getString(R.string.getting_prepayid));
    }

    @Override
    protected void onPostExecute(Map<String, String> result) {
      if (dialog != null) {
        dialog.dismiss();
      }
      sb.append("prepay_id\n" + result.get("prepay_id") + "\n\n");
      show.setText(sb.toString());

      resultunifiedorder = result;
    }

    @Override
    protected void onCancelled() {
      super.onCancelled();
    }

    @Override
    protected Map<String, String> doInBackground(Void... params) {

      String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
      String entity = genProductArgs("test");

      Log.e("orion", entity);

      byte[] buf = Util.httpPost(url, entity);

      String content = new String(buf);
      Log.e("orion", content);
      Map<String, String> xml = decodeXml(content);

      return xml;
    }
  }

  public Map<String, String> decodeXml(String content) {

    try {
      Map<String, String> xml = new HashMap<String, String>();
      XmlPullParser parser = Xml.newPullParser();
      parser.setInput(new StringReader(content));
      int event = parser.getEventType();
      while (event != XmlPullParser.END_DOCUMENT) {

        String nodeName = parser.getName();
        switch (event) {
          case XmlPullParser.START_DOCUMENT:
            break;
          case XmlPullParser.START_TAG:
            if ("xml".equals(nodeName) == false) {
              // 实例化student对象
              xml.put(nodeName, parser.nextText());
            }
            break;
          case XmlPullParser.END_TAG:
            break;
        }
        event = parser.next();
      }

      return xml;
    } catch (Exception e) {
      Log.e("orion", e.toString());
    }
    return null;
  }

  private String genNonceStr() {
    Random random = new Random();
    return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
  }

  private long genTimeStamp() {
    return System.currentTimeMillis() / 1000;
  }

  //    private String genOutTradNo() {
  //        Random random = new Random();
  //        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
  //    }

  private String genOutTradNo(String no) {
    return no;
    //        Random random = new Random();
    //        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
  }

  //
  private String genProductArgs(String tradeno) {
    StringBuffer xml = new StringBuffer();

    try {
      String nonceStr = genNonceStr();

      xml.append("</xml>");
      List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
      packageParams.add(new BasicNameValuePair("appid", Constants.APP_ID));
      packageParams.add(new BasicNameValuePair("body", "weixin"));
      packageParams.add(new BasicNameValuePair("mch_id", Constants.MCH_ID));
      packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
      packageParams.add(
          new BasicNameValuePair(
              "notify_url", AppConfig.APP_SERVER + ApiService.INTERFACE_WEIXINPAY));
      packageParams.add(new BasicNameValuePair("out_trade_no", genOutTradNo(tradeno)));
      packageParams.add(new BasicNameValuePair("spbill_create_ip", "127.0.0.1"));
      packageParams.add(new BasicNameValuePair("total_fee", "1"));
      packageParams.add(new BasicNameValuePair("trade_type", "APP"));

      String sign = genPackageSign(packageParams);
      packageParams.add(new BasicNameValuePair("sign", sign));

      String xmlstring = toXml(packageParams);

      return xmlstring;

    } catch (Exception e) {
      return null;
    }
  }

  private void genPayReq() {

    req.appId = Constants.APP_ID;
    req.partnerId = Constants.MCH_ID;
    req.prepayId = resultunifiedorder.get("prepay_id");
    req.packageValue = "Sign=WXPay";
    req.nonceStr = genNonceStr();
    req.timeStamp = String.valueOf(genTimeStamp());

    List<NameValuePair> signParams = new LinkedList<NameValuePair>();
    signParams.add(new BasicNameValuePair("appid", req.appId));
    signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
    signParams.add(new BasicNameValuePair("package", req.packageValue));
    signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
    signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
    signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

    req.sign = genAppSign(signParams);

    sb.append("sign\n" + req.sign + "\n\n");

    show.setText(sb.toString());

    Log.e("orion", signParams.toString());
  }

  private void sendPayReq() {
    msgApi.registerApp(Constants.APP_ID);
    msgApi.sendReq(req);
  }
}
Esempio n. 25
0
  private void shareToWeixin(
      Context mcontext, String shareUrl, String title, String des, Drawable mDrawable, int type) {
    Bitmap b = null;
    try {
      IWXAPI api = WXAPIFactory.createWXAPI(act, APP_ID);
      api.registerApp(APP_ID);
      if (!api.isWXAppInstalled()) {
        Toast.makeText(
                act,
                act.getResources().getString(R.string.weixinsdk_demo_has_not_installed_weibo),
                Toast.LENGTH_SHORT)
            .show();
        return;
      }
      WXMediaMessage msg = null;
      switch (type) {
        case Share_Text_Type:
          WXTextObject textObj = new WXTextObject();
          textObj.text = title;
          msg = new WXMediaMessage();
          msg.mediaObject = textObj;
          msg.description = title;
          break;
        case Share_Webpage_Type:
          WXWebpageObject webpage = new WXWebpageObject();
          webpage.webpageUrl = shareUrl;
          msg = new WXMediaMessage(webpage);
          msg.title = title;
          msg.description = des;
          break;
      }

      if (type == Share_Webpage_Type && mDrawable != null) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) mDrawable;
        b = bitmapDrawable.getBitmap();
        b = zoomImg(b, 100);
        if (b == null) {
          bitmapDrawable =
              ((BitmapDrawable) context.getResources().getDrawable(R.drawable.ic_launcher));
          b = bitmapDrawable.getBitmap();
        }
        msg.thumbData = bmpToByteArray(b, true);
      }
      SendMessageToWX.Req req = new SendMessageToWX.Req();
      if (type == Share_Text_Type) req.transaction = buildTransaction("text");
      else if (type == Share_Webpage_Type) {
        req.transaction = buildTransaction("webpage");
        msg.title = title;
        msg.description = des;
      }
      req.message = msg;
      req.scene = SendMessageToWX.Req.WXSceneSession;
      api.sendReq(req);
    } catch (Exception e) {
      e.printStackTrace();
      Toast.makeText(mcontext, mcontext.getString(R.string.share_weixin), 300).show();
    } finally {
      if (b != null) {
        b = null;
      }
    }
  }
Esempio n. 26
0
 public static IWXAPI getWechatApi(Context context) {
   return WXAPIFactory.createWXAPI(context, Constants.APP_ID, false);
 }