微信支付接入准备与Demo引入
在软件开发过程中,支付功能是常见需求,目前主流方式包括支付宝和微信支付。相比之下,支付宝的文档体系更为完善,配置与调用逻辑也相对简单,此处不再赘述。
首先,需前往微信官网下载服务端Demo,下载地址为:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1
虽然微信提供的Demo主要针对公众号支付,且预下单等操作理论上可由前端完成,但官方建议由服务端处理以确保安全。下载后,将Demo引入项目即可。需注意,若涉及公众号支付,核心类文件WxPay.JsApiPay.php位于example目录下。
接下来进行引用与实现。本文以ThinkPHP框架为例,演示移动端及公众号支付(含获取OpenID)的功能。为便于理解,以下代码提取了部分类方法,结构略显松散,敬请谅解。
ThinkPHP框架下支付流程实现
/* 微信APP下支付预下单 */
public function wxAppOrder(){
//TODO:首先获取订单详情,例如传递过来订单号或订单id,获取订单的详情信息,例如将取出的数据存放入$user_order_info数组,订单中包含的商品在$user_order_product_info之中。
/* 向微信发起请求 */
vendor('WxpayAPI.lib.WxPay','','.Api.php');
vendor('WxpayAPI.lib.WxPay','','.Data.php');//生成数据
//统一下单输入对象
$order_info= new WxPayUnifiedOrder();
$order_info->SetOut_trade_no($user_order_info['orderNo']);//商品订单号
$body=$user_order_product_info['productName'];
// $body=iconv('UTF-8', 'ISO-8859-1', $user_order_product_info['productName']);
$order_info->SetBody($body);//商品描述
$order_info->SetTrade_type('CNY');//软妹币
$order_info->SetTotal_fee(intval($user_order_info['sumPrice']*100));//总金额,以分为单位
$order_info->SetTrade_type('APP');//交易类型
$order_info->SetAppid(C('wxAPPID'));
$order_info->SetMch_id(C('wxMCHID'));
$order_info->SetNotify_url('你的回调地址');
$order_info->SetSign();
//进行统一支付
$wxpay=new WxPayApi();
$order_result=$wxpay->unifiedOrder($order_info);//统一下单
if ($order_result['return_code']=='FAIL') {
$arr=array(
'resultCode'=>'99',
'resultDesc'=>$order_result['return_msg'],
'resultObj'=>array(''=>''),
);
echo JSON($arr);
exit();
}
if ($order_result['result_code']=='SUCCESS') {
//预下单成功后,重新签名返回给移动端
$wxpay_result=new WxPayResults();
$timestamp=time();
$wxpay_result->SetData('appid', $order_result['appid']);
$wxpay_result->SetData('partnerid', $order_result['mch_id']);
$wxpay_result->SetData('prepayid', $order_result['prepay_id']);
$wxpay_result->SetData('timestamp', $timestamp);
$wxpay_result->SetData('noncestr', $order_result['nonce_str']);
$wxpay_result->SetData('package', 'Sign=WXPay');
// $wxpay_result->SetData('key', C('wxKEY'));
//上方注释的代码是再签名中必要的一步,只是这个包含在了微信demo的类中,如果像该项目中既有app支付,又有公众号支付,最好是注释类中代码,并自己写入
$resign_result=$wxpay_result->SetSign();
//处理返回数据
$result=array(
'appid'=>$order_result['appid'],//appid
'partnerid'=>$order_result['mch_id'],//商户号
'prepayid'=>$order_result['prepay_id'],//与支付id
'package'=>'Sign=WXPay',
'noncestr'=>$order_result['nonce_str'],
'timestamp'=>$timestamp,
'sign'=>$resign_result,
);
$arr=array(
'resultCode'=>'00',
'resultDesc'=>'成功',
'resultObj'=>$result,
);
echo JSON($arr);
exit();
}else{
$arr=array(
'resultCode'=>'99',
'resultDesc'=>'失败',
'resultObj'=>$order_result,
);
echo JSON($arr);
exit();
}
}
/* 微信支付回调函数 */
public function wxpayNotify(){
vendor('WxpayAPI.lib.Logwx','','.Log.php');//在回调中最好是引入日志进行记录,在这里因为Log类与thinkphp中的log类重复,需要进行处理
$handle=new CLogFileHandler('./Public/wxlog.txt');
$log=Logwx::Init($handle);
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];//获取数据
vendor('WxpayAPI.lib.WxPay','','.Api.php');
vendor('WxpayAPI.lib.WxPay','','.Data.php');
$wxpay=new WxPayApi();
$notify=new WxPayNotifyReply();
$result=WxPayResults::Init($xml);//获取数据并转换为数组
if ($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS') {//此字段是通信标识,非交易标识,交易是否成功需要查看result_code来判断
//TODO:进行数据库操作的业务逻辑处理,假设其成功与否的数据为$res
if ($res) {
$log->INFO('订单:'.$result['out_trade_no'].'支付成功');
$notify->SetReturn_code('SUCCESS');
$notify->SetReturn_msg('OK');
$notify->SetSign();
}else{
$log->ERROR('微信支付失败');
$notify->SetReturn_code('FAIL');
$notify->SetReturn_msg('客户服务器错误');
}
}else{
$log->ERROR('微信回调返回错误');
$notify->SetReturn_code('FAIL');
$notify->SetReturn_msg('微信支付失败');
}
//返回微信端
$wxpay->replyNotify($notify->ToXml());
}
/* 微信公众账号下单
* 获取code等信息
* 跳转至获取信息
* */
public function wxPubOrder(){
//此流程中
$orderId=$_GET['orderId'];
//注意:此处如果想要回调成功,需要在微信公众平台设置回调域名
// print_r('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.C('wxAPPID').'&redirect_uri='.'http://你的域名/Pay/getOpenid/orderId/'.$orderId.'&response_type=code&scope=snsapi_base&state=123#wechat_redirect');
// exit();
header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.'*******'.'&redirect_uri='.urlencode('http://*****/Pay/getOpenid/orderId/'.$orderId).'&response_type=code&scope=snsapi_base&state=123#wechat_redirect');
exit();
}
/* 微信获取openid,跳转到微信同意下单接口 */
public function getOpenid(){
//code
$code=$_GET['code'];
$state=$_GET['state'];
$orderId=$_GET['orderId'];
$appid='******';
$appsecret='******';
//获取openid
$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_token_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
$json_obj = json_decode($res,true);
$openId=$json_obj['openid'];
// 跳转到预下单
// echo $openId;exit();
$url='http://******/html5/#/pay/'.$orderId.'openid='.$openId;
header('Location:'.$url);
}
/* 微信公众账号统一下单 */
public function wxOrder(){
$orderId=$_GET['orderId'];
$openId=$_GET['openId'];
if (empty($orderId)||empty($openId)) {
$arr=array(
'resultCode'=>'66',
'resultDesc'=>'缺少参数',
'resultObj'=>array(),
);
echo JSON($arr);
exit();
}
//TODO:获取订单和订单商品信息,分别存储在$user_order_info中和$user_order_good_info中
if (empty($user_order_info)) {
$arr=array(
'resultCode'=>'99',
'resultDesc'=>'不存在该订单',
'resultObj'=>array(),
);
echo JSON($arr);
exit();
}
/* 向微信发起请求 */
vendor('WxpayAPI.lib.WxPay','','.Api.php');
vendor('WxpayAPI.lib.WxPay','','.Data.php');//生成数据
// vendor('WxpayAPI.lib.WxPay','','.JsApiPay.php');
//统一下单输入对象
$order_info= new WxPayUnifiedOrder();
$wxpay=new WxPayApi();
$order_info->SetMch_id('***');//商户号
$order_info->SetAppid('****');//微信号APPID//wx70a40dfa2711c4fe
$order_info->SetOut_trade_no($user_order_info['orderNo']);//商品订单号
$order_info->SetBody($user_order_good_info['productName']);//商品描述
$order_info->SetTrade_type('CNY');//软妹币
$order_info->SetTotal_fee(intval($user_order_info['sumPrice']*100));//总金额,以分为单位
$order_info->SetTrade_type('JSAPI');//交易类型
$order_info->SetNonce_str($wxpay->getNonceStr(32));
$order_info->SetSpbill_create_ip('1.1.1.1');
// $order_info->SetOpenid($user_info['openId']);
$order_info->SetOpenid($openId);
//TODO:
$order_info->SetNotify_url('http://****/Pay/wxpayNotify');
$order_info->SetSign();//设置签名
//进行统一支付
$order_result=$wxpay->unifiedOrder($order_info);//统一下单
//同意下单后再加
if ($order_result['return_code']=='FAIL') {
$arr=array(
'resultCode'=>'99',
'resultDesc'=>$order_result['return_code'].':'.$order_result['return_msg'],
'resultObj'=>array(),
);
echo JSON($arr);
exit();
}
if ($order_result['result_code']=='SUCCESS') {
$jsapi = new WxPayJsApiPay();
$jsapi->SetAppid($order_result["appid"]);
$timeStamp = time();
$jsapi->SetTimeStamp("$timeStamp");
$jsapi->SetNonceStr(WxPayApi::getNonceStr());
$jsapi->SetPackage("prepay_id=" . $order_result['prepay_id']);
$jsapi->SetSignType("MD5");
$jsapi->SetPaySign($jsapi->MakeSign());
$order_result = $jsapi->GetValues();
// print_r($order_result);exit();
$arr=array(
'resultCode'=>'00',
'resultDesc'=>'成功',
'resultObj'=>$order_result,
);
echo JSON($arr);
exit();
}else{
$arr=array(
'resultCode'=>'99',
'resultDesc'=>'失败',
'resultObj'=>$order_result,
);
echo JSON($arr);
exit();
}
}
常见支付问题排查与解决思路
上述即为完整的支付流程。在实际操作中可能遇到诸多问题,以下梳理了几种高频问题的解决思路:
- 1、APP统一下单后数据返回前端,调用时报签名错误:首先检查秘钥信息是否正确,注意移动端与公众号的秘钥不同。由于类内部会重新签名,可注释掉微信官方Demo中直接调用配置文件的部分。
- 2、公众号获取OpenID时出现跨域错误:参考YII2框架中\yii::$app->response->header的remove方法,移除相关报头即可解决。
- 3、关于微信支付的其他配置,如公众号支付的白名单设置、测试目录配置等,此处不再详述,建议自行搜索相关资料。
过程中可能还会遇到其他问题,此处不一一列举。如有疑问,欢迎在评论区留言,共同讨论学习,共同进步。
总结
以上就是本文的全部内容,希望能为您的学习或工作提供参考,感谢支持。如需了解更多相关内容,请查看下方相关链接。