微信公众号支付入坑-01

微信支付入坑系列-01

要使用微信支付,需要以下几个步骤:
1.开通微信支付功能,开通后,就可以拿到商户id和商户api密钥,有了这两个必须的东西,就可以调用微信统一支付接口,拿到微信预支付prepayid了.有了prepayid,就可以在网页中调用jsapi了。
2.重点是怎么拿到prepayid呢?很简单,调用post请求道https://api.mch.weixin.qq.com/pay/unifiedorder地址就可以了,很简单吧。咋一看确实简单,但这里面隐藏了好几个坑。
3.要拿到peipayid,需要传递一组xml数据,对应java攻城狮来说,一般都会写个model,填充数据,然后将model转换为xml字符串,然后跟随post请求一起发送出去。
4.在一组xml数据中,有一个签名,初次遇到的人肯定都会蒙。这个签名要怎么签呢,要把你所有要传递给服务器的数据进行处理。记住:是所有要传递给服务器(腾讯)的数据,除了sign这个数据外的所有数据。sign也要被传送到服务器端去。

一般是这样的:
               private String appid;// 公众账号ID
               private String mch_id;// 商户号
               private String device_info;// 设备号
               private String nonce_str;// 随机字符串
               private String sign;// 签名
               private String body;// 商品描述
               private String detail;// 商品详情
               private String attach;// 附加数据
               ... ...
          将这些字段先进行排序,字典排序,直接调用Arrays.sort(String[]);这样就排序完了,然后再拼接成一个字符串,appid=123&mch_id=123......以此类推,最后在加上商品api密钥key=123.完了之后,进行md5转换

5.我遇到的下一个坑,也很简单,但折腾了我很久。我将创建好的model转换为xml,使用的是以下代码:XStream xStream = new XStream();
        xStream.alias("xml", object.getClass());
         转换结果如下:
         
 <appid>xxxxxxxxxxxxx</appid>
  <mch__id>xxxxxxxxxxxx</mch__id>
  <nonce__str>1add1a30ac87aa2db72f57a2375d8fec</nonce__str>
  <sign>C939DCA5210FEDF5C9651412C966EA01</sign>
  <body>test</body>
  <out__trade__no>1ad41a30ac87aa2db72f57a2375d8fec</out__trade__no>
  <total__fee>1</total__fee>
  <spbill__create__ip>xxx.xx.xx.xx</spbill__create__ip>
  <notify__url>xxxxxxxxxxxxxxxx</notify__url>
  <trade__type>JSAPI</trade__type>
  <openid>xxxxxxxxxxx</openid>
</xml>
     乍一看,这是没有问题的,其实应该是这样的:
     <xml><appid><![CDATA[xxxxxxxxxxx]]></appid><mch_id><![CDATA[xxxxxxxxxx]]></mch_id><nonce_str><![CDATA[1add1a30ac87aa2db72f57a2375d8fec]]></nonce_str></xml>
       也就是说:只要是字符串,就得用<![CDATA[   ]]>包裹起来,整型数据不用包裹,没有其他型号的数据了

 

posted @ 2017-11-14 15:48  飘絮不飘  阅读(391)  评论(0编辑  收藏  举报