コード例 #1
0
ファイル: main.py プロジェクト: dungagan/mpesaapirouter
    def get(self):

        if 'amount' in request.args:
            phone = int(request.args['id'])
            amount = int(request.args['amount'])
            transid = str(request.args['transid'])
            package = str(request.args['package'])

            api_context = APIContext()
            api_context.api_key = '51nb4dn05870mc92zng4smucl8ghohc6'
            api_context.public_key = 'MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAmptSWqV7cGUUJJhUBxsMLonux24u+FoTlrb+4Kgc6092JIszmI1QUoMohaDDXSVueXx6IXwYGsjjWY32HGXj1iQhkALXfObJ4DqXn5h6E8y5/xQYNAyd5bpN5Z8r892B6toGzZQVB7qtebH4apDjmvTi5FGZVjVYxalyyQkj4uQbbRQjgCkubSi45Xl4CGtLqZztsKssWz3mcKncgTnq3DHGYYEYiKq0xIj100LGbnvNz20Sgqmw/cH+Bua4GJsWYLEqf/h/yiMgiBbxFxsnwZl0im5vXDlwKPw+QnO2fscDhxZFAwV06bgG0oEoWm9FnjMsfvwm0rUNYFlZ+TOtCEhmhtFp+Tsx9jPCuOd5h2emGdSKD8A6jtwhNa7oQ8RtLEEqwAn44orENa1ibOkxMiiiFpmmJkwgZPOG/zMCjXIrrhDWTDUOZaPx/lEQoInJoE2i43VN/HTGCCw8dKQAwg0jsEXau5ixD0GUothqvuX3B9taoeoFAIvUPEq35YulprMM7ThdKodSHvhnwKG82dCsodRwY428kg2xM/UjiTENog4B6zzZfPhMxFlOSFX4MnrqkAS+8Jamhy1GgoHkEMrsT5+/ofjCx0HjKbT5NuA2V/lmzgJLl3jIERadLzuTYnKGWxVJcGLkWXlEPYLbiaKzbJb2sYxt+Kt5OxQqC1MCAwEAAQ=='
            api_context.ssl = True
            api_context.method_type = APIMethodType.POST
            api_context.address = 'api.sandbox.vm.co.mz'
            api_context.port = 18352
            api_context.path = '/ipg/v1x/c2bPayment/singleStage/'

            api_context.add_header('Origin', '*')

            api_context.add_parameter('input_TransactionReference', package)
            api_context.add_parameter('input_CustomerMSISDN', phone)
            api_context.add_parameter('input_Amount', amount)
            api_context.add_parameter('input_ThirdPartyReference', transid)
            api_context.add_parameter('input_ServiceProviderCode', '171717')

            api_request = APIRequest(api_context)
            result = api_request.execute()
            pprint(result.body)
            print('fired  on success')
            data = result.body  # read CSV
            return {'d': data}, 200  # return data and 200 OK code
        pass
コード例 #2
0
def send_payment(request):
    package = Package.objects.get(id=int(request.GET['package']))
    message = 'Pagamento efectuado com sucesso.'
    status = 201
    user = request.user
    token = uuid.uuid4()
    PaymentPackage.objects.create(
        user=request.user,
        package=package,
        payment_method=PaymentMethod.objects.get(id=1),
        token=token,
        expire_at=now() + relativedelta(months=1),
        mobile=request.GET['phone'],
        amount=package.price)
    if not package.price == 0:
        key = 'dsf4utfandhnbwnxtrrs8rlbq97o0x8g'
        pky = 'MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAyrOP7fgXIJgJyp6nP/Vtlu8kW94Qu+gJjfMaTNOSd/mQJChqXiMWsZPH8uOoZGeR/9m7Y8vAU83D96usXUaKoDYiVmxoMBkfmw8DJAtHHt/8LWDdoAS/kpXyZJ5dt19Pv+rTApcjg7AoGczT+yIU7xp4Ku23EqQz70V5Rud+Qgerf6So28Pt3qZ9hxgUA6lgF7OjoYOIAKPqg07pHp2eOp4P6oQW8oXsS+cQkaPVo3nM1f+fctFGQtgLJ0y5VG61ZiWWWFMOjYFkBSbNOyJpQVcMKPcfdDRKq+9r5DFLtFGztPYIAovBm3a1Q6XYDkGYZWtnD8mDJxgEiHWCzog0wZqJtfNREnLf1g2ZOanTDcrEFzsnP2MQwIatV8M6q/fYrh5WejlNm4ujnKUVbnPMYH0wcbXQifSDhg2jcnRLHh9CF9iabkxAzjbYkaG1qa4zG+bCidLCRe0cEQvt0+/lQ40yESvpWF60omTy1dLSd10gl2//0v4IMjLMn9tgxhPp9c+C2Aw7x2Yjx3GquSYhU6IL41lrURwDuCQpg3F30QwIHgy1D8xIfQzno3XywiiUvoq4YfCkN9WiyKz0btD6ZX02RRK6DrXTFefeKjWf0RHREHlfwkhesZ4X168Lxe9iCWjP2d0xUB+lr10835ZUpYYIr4Gon9NTjkoOGwFyS5ECAwEAAQ=='
        skode = '900275'

        api_context = APIContext()
        api_context.api_key = key  # 'b5zh48dd1ru963gcjnl4pq0d5ip0cdq0'
        api_context.public_key = pky
        api_context.ssl = True
        api_context.method_type = APIMethodType.POST
        api_context.address = 'api.vm.co.mz'  # sandbox
        api_context.port = 18352
        api_context.path = '/ipg/v1x/c2bPayment/singleStage/'

        api_context.add_header('Origin', '*')

        api_context.add_parameter('input_TransactionReference',
                                  str(now().year) + '00' + str(user.id))
        api_context.add_parameter('input_CustomerMSISDN',
                                  '258' + request.GET['phone'])
        api_context.add_parameter('input_Amount', str(package.price))
        api_context.add_parameter('input_ThirdPartyReference',
                                  'PC000' + str(package.id))
        api_context.add_parameter('input_ServiceProviderCode',
                                  skode)  # '171717'

        api_request = APIRequest(api_context)
        result = api_request.execute()

        message = 'Pagamento sem sucesso, por favor tente novamente em 5 minutos.'
        status = result.status_code

        if status == 201 or status == 200:
            message = 'Pagamento efectuado com Sucesso!'

        if status == 422:
            message = 'Saldo insuficiente para completar o pagamento, por favor tente novamente!'

    return Response({'status': status, 'token': token, 'message': message})
コード例 #3
0
ファイル: mpesa.py プロジェクト: ZendaInnocent/SAAS-kit
    def get_encrypted_api_key(self) -> str:
        """A function to return encrypted API key

        :return: Encrypted API key
        :rtype: str
        """
        return APIRequest(self.context).create_bearer_token()
コード例 #4
0
ファイル: mpesa.py プロジェクト: ZendaInnocent/SAAS-kit
    def _get_api_response(self, context: dict) -> dict:
        """A function for getting results from API call.

        :param context: A dictionary containing all the necessary
        parameters for making API call.
        :type context: dict
        :raises Exception: Exception raised when API call fails.
        :return: Response from API call.
        :rtype: dict
        """
        response = None
        try:
            response = APIRequest(context).execute()
        except Exception as e:
            print('Call Failed: ', e)

        if response is None:
            raise Exception('API call failed to get result. Please check.')
        else:
            return response
コード例 #5
0
ファイル: mpesa.py プロジェクト: ZendaInnocent/SAAS-kit
    def get_session_id(self, path: str = get_session_url) -> str:
        """A function to generate valid Session ID needed to transact on M-Pesa
        using OpenAPI.

        :param path: url, defaults to get_session_url
        :type path: string, optional
        :raises Exception: When request fails, exception must be raised.
        :return: A valid Session ID
        :rtype: str
        """
        self.context.update({'method_type': APIMethodType.GET, 'path': path})

        response = None

        try:
            response = APIRequest(self.context).execute()
        except Exception as e:
            print('Call Failed: ', e)

        if response is None:
            raise Exception(
                'SessionKey call failed to get response. Please check.')
        else:
            return response.body['output_SessionID']
コード例 #6
0
def paymentView(request):

    selected_plan = get_selected_plan(request)
    plans = Plan.objects.get(name=selected_plan)

    business = Business.objects.get(user=request.user)

    current_subscription = get_user_plan(request)

    reference_no = str(request.user.id) + str(current_subscription.id) + \
        datetime.now().strftime('%Y%m%d%H%M%S')

    print('reference_no:', reference_no)

    if request.method == 'POST':
        form = PaymentForm(request.POST)
        if form.is_valid():

            # Begin payment processing
            public_key = settings.PUBLIC_KEY

            # Create Context with API to request a Session ID
            api_context = APIContext()

            # Api key
            api_context.api_key = settings.API_KEY

            # Public key
            api_context.public_key = public_key

            # Use ssl/https
            api_context.ssl = True

            # Method type (can be GET/POST/PUT)
            api_context.method_type = APIMethodType.GET

            # API address
            api_context.address = 'openapi.m-pesa.com'

            # API Port
            api_context.port = 443

            # API Path
            api_context.path = '/sandbox/ipg/v2/vodacomTZN/getSession/'

            # Add/update headers
            api_context.add_header('Origin', '*')

            # Parameters can be added to the call as well that on POST will be in JSON format and on GET will be URL parameters
            # api_context.add_parameter('key', 'value')

            # Do the API call and put result in a response packet
            api_request = APIRequest(api_context)

            # Do the API call and put result in a response packet
            result = None
            try:
                result = api_request.execute()
            except Exception as e:
                print('Call Failed: ' + e)

            if result is None:
                raise Exception(
                    'SessionKey call failed to get result. Please check.')

            # The above call issued a sessionID
            api_context = APIContext()
            api_context.api_key = result.body['output_SessionID']
            api_context.public_key = public_key
            api_context.ssl = True
            api_context.method_type = APIMethodType.POST
            api_context.address = 'openapi.m-pesa.com'
            api_context.port = 443
            api_context.path = '/sandbox/ipg/v2/vodacomTZN/c2bPayment/singleStage/'
            api_context.add_header('Origin', '*')

            # Input Variables
            amount = plans.price
            phone = request.POST.get('phone')
            desc = plans.name

            api_context.add_parameter('input_Amount', amount)
            api_context.add_parameter('input_Country', 'TZN')
            api_context.add_parameter('input_Currency', 'TZS')
            # phone number from customer
            api_context.add_parameter('input_CustomerMSISDN', '000000000001')
            api_context.add_parameter('input_ServiceProviderCode', '000000')
            api_context.add_parameter(
                'input_ThirdPartyConversationID', 'asv02e5958774f7ba228d83d0d689761')
            api_context.add_parameter(
                'input_TransactionReference', reference_no)
            api_context.add_parameter('input_PurchasedItemsDesc', desc)

            api_request = APIRequest(api_context)

            sleep(30)

            result = None

            try:
                result = api_request.execute()
            except Exception as e:
                print('Call Failed: ' + e)

            if result is None:
                raise Exception('API call failed to get result. Please check.')


            if result.body['output_ResponseCode'] == 'INS-0':

                # update/downgrade subscriptions
                ends_time = timezone.now() + timedelta(days=plans.duration_days)
                Subscription.objects.filter(business=request.user.business).update(
                    plan=plans.id,
                    start_time=timezone.now(),
                    ends_time=ends_time,
                    paid_status=True,
                )

                # save transactionID,transactionID
                payment = form.save(commit=False)
                payment.user_id = request.user.id
                payment.transactionID = result.body['output_TransactionID']
                payment.conversationID = result.body['output_ConversationID']
                payment.reference_no = reference_no
                payment.save()

                return HttpResponse('Your Payment was Successfully sent!')

            elif result.body['output_ResponseCode'] == 'INS-1':
                messages.add_message(request, messages.ERROR, 'Internal Error')

            elif result.body['output_ResponseCode'] == 'INS-6':
                messages.add_message(
                    request, messages.ERROR, 'Transaction Failed')

            elif result.body['output_ResponseCode'] == 'INS-9':
                messages.add_message(
                    request, messages.ERROR, 'Request timeout')

            elif result.body['output_ResponseCode'] == 'INS-10':
                messages.add_message(
                    request, messages.ERROR, 'Duplicate Transaction')

            elif result.body['output_ResponseCode'] == 'INS-2006':
                messages.add_message(
                    request, messages.ERROR, 'Insufficient balance')

            else:
                messages.add_message(
                    request, messages.ERROR,
                    'Configuration Error, contact with support team')

    else:
        form = PaymentForm()
    context = {'form': form, 'plans': plans, 'reference_no': reference_no}

    return render(request, 'membership/payment.html', context)
コード例 #7
0
ファイル: payment.py プロジェクト: devmedtz/ecommerce
def MakePaymentView(request, order_id):

    order = Order.objects.get(id=order_id)
    cart_price = order.cart_total

    if request.method == 'POST':
        form = MakePaymentForm(request.POST or None)
        if form.is_valid():

            #Begin payment processing
            public_key = settings.PUBLIC_KEY

            # Create Context with API to request a Session ID
            api_context = APIContext()

            # Api key
            api_context.api_key = settings.API_KEY

            # Public key
            api_context.public_key = public_key

            # Use ssl/https
            api_context.ssl = True

            # Method type (can be GET/POST/PUT)
            api_context.method_type = APIMethodType.GET

            # API address
            api_context.address = 'openapi.m-pesa.com'

            # API Port
            api_context.port = 443

            # API Path
            api_context.path = '/sandbox/ipg/v2/vodacomTZN/getSession/'

            # Add/update headers
            api_context.add_header('Origin', '*')

            # Parameters can be added to the call as well that on POST will be in JSON format and on GET will be URL parameters
            # api_context.add_parameter('key', 'value')

            #Do the API call and put result in a response packet
            api_request = APIRequest(api_context)

            # Do the API call and put result in a response packet
            result = None
            try:
                result = api_request.execute()
            except Exception as e:
                print('Call Failed: ' + e)

            if result is None:
                raise Exception(
                    'SessionKey call failed to get result. Please check.')

            # Display results
            print(result.status_code)
            print(result.headers)
            print(result.body)

            # The above call issued a sessionID
            api_context = APIContext()
            api_context.api_key = result.body['output_SessionID']
            api_context.public_key = public_key
            api_context.ssl = True
            api_context.method_type = APIMethodType.POST
            api_context.address = 'openapi.m-pesa.com'
            api_context.port = 443
            api_context.path = '/sandbox/ipg/v2/vodacomTZN/c2bPayment/singleStage/'
            api_context.add_header('Origin',
                                   '*')  #127.0.0.1:8000 or Domain name

            phone = request.POST.get('phone')

            amount = str(cart_price)
            phone = str(phone)
            item_id = str(order_id)

            print('cart_price', cart_price)
            print('phone', phone)
            print('item_id', item_id)

            api_context.add_parameter('input_Amount', amount)
            api_context.add_parameter('input_Country', 'TZN')
            api_context.add_parameter('input_Currency', 'TZS')
            api_context.add_parameter('input_CustomerMSISDN', '000000000001')
            api_context.add_parameter('input_ServiceProviderCode', '000000')
            api_context.add_parameter('input_ThirdPartyConversationID',
                                      'asv02e5958774f7ba228d83d0d689761')
            api_context.add_parameter('input_TransactionReference', item_id)
            api_context.add_parameter('input_PurchasedItemsDesc', item_id)

            api_request = APIRequest(api_context)

            sleep(30)

            result = None

            try:
                result = api_request.execute()
            except Exception as e:
                print('Call Failed: ' + e)

            if result is None:
                raise Exception('API call failed to get result. Please check.')

            print(result.status_code)
            print(result.headers)
            print(result.body)

            if result.body['output_ResponseCode'] == 'INS-0':
                payment = form.save(commit=False)
                payment.customer = request.user.customer
                payment.order_id = order_id
                payment.save()

                #save transactionID and mark paid status true
                order.transaction_id = result.body['output_TransactionID']
                order.paid_status = True
                order.save()
                return HttpResponse('Your Payment was Successfully sent!')

            elif result.body['output_ResponseCode'] == 'INS-1':
                messages.add_message(request, messages.ERROR, 'Internal Error')

            elif result.body['output_ResponseCode'] == 'INS-6':
                messages.add_message(request, messages.ERROR,
                                     'Transaction Failed')

            elif result.body['output_ResponseCode'] == 'INS-9':
                messages.add_message(request, messages.ERROR,
                                     'Request timeout')

            elif result.body['output_ResponseCode'] == 'INS-10':
                messages.add_message(request, messages.ERROR,
                                     'Duplicate Transaction')

            else:
                messages.add_message(request, messages.ERROR,
                                     'Configuration Error')

    else:
        form = MakePaymentForm()

    context = {'form': form, 'order_id': order_id, 'cart_price': cart_price}

    return render(request, 'store/payment.html', context)